Get list of all routes defined in the Flask app
All the routes for an application are stored on app.url_map
which is an instance of werkzeug.routing.Map
. You can iterate over the Rule
instances by using the iter_rules
method:
from flask import Flask, url_for
app = Flask(__name__)
def has_no_empty_params(rule):
defaults = rule.defaults if rule.defaults is not None else ()
arguments = rule.arguments if rule.arguments is not None else ()
return len(defaults) >= len(arguments)
@app.route("/site-map")
def site_map():
links = []
for rule in app.url_map.iter_rules():
# Filter out rules we can't navigate to in a browser
# and rules that require parameters
if "GET" in rule.methods and has_no_empty_params(rule):
url = url_for(rule.endpoint, **(rule.defaults or {}))
links.append((url, rule.endpoint))
# links is now a list of url, endpoint tuples
See Display links to new webpages created for a bit more information.
List all available routes in Flask, along with corresponding functions' docstrings
There is app.view_functions
. I think that is exactly what you want.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods = ['GET'])
def this_func():
"""This is a function. It does nothing."""
return jsonify({ 'result': '' })
@app.route('/api/help', methods = ['GET'])
def help():
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list)
if __name__ == '__main__':
app.run(debug=True)
Get list of all routes defined in the Falcon app
The below code will return a list of tuple with URL and their respective Resources:
def get_all_routes(api):
routes_list = []
def get_children(node):
if len(node.children):
for child_node in node.children:
get_children(child_node)
else:
routes_list.append((node.uri_template, node.resource))
[get_children(node) for node in api._router._roots]
return routes_list
Output
[
('/v1/things', <v1.v1_app.ThingsResource object at 0x7f555186de10>),
('/v2/things', <v2.v2_app.ThingsResource object at 0x7f5551871470>),
('/v3/things/{name}', <v3.v3_app.ThingsResource object at 0x7f5551871ba8>)
]
I have read the package and derived this, however, I don't know any builtin method that will return this result.
If you don't like the above function, You can achieve something similar by extending the API class.
I have made a Github repo for versioning the Falcon app, from which you can get an idea of separating the URLs and their relative resources. Github Link
You can have a list of routes and add them by Extended the API class
URLs and Resources will be like:
from v1.v1_app import things
urls = [
('/things', things),
]
Catch all routes for Flask
You can follow this guideline: https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations
from flask import Flask
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
Flask API - List all resources added
You can use app.url_map.iter_values()
Following is an example
@app.route('/')
def hi():
return 'Hello World!'
@app.route('/hi')
def hi():
return 'Hi!'
@app.route('/hello')
def hello():
return 'Hello World!'
def routes():
routes = []
for route in app.url_map.iter_rules():
routes.append('%s' % route)
print(routes)
['/hello', '/hi', '/']
How do I make an error handler with flask
welcome to stackoverflow!
To create a error handler of any error code in flask you must do the following, for my example I will use a 404
error as requested in the post:
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
If you want to error handle a 505
just substitut the 404
for a 505
and create a new html file in templates
Is there a way to make all pages in a Flask app show the same content?
You might not even need flask for this and can control it on other levels, but for flask here are good examples to do so.
It is suggested to add @app.before_request
and check maintenance flag. (@app.before_request
will be called before all request, so you do not need to do maintenance check for all 50 routes).
@app.before_request
def check_under_maintenance():
if maintenance_mode == 1: #this flag can be anything, read from file,db or anything
abort(503)
@app.route('/')
def index():
return "This is Admiral Ackbar, over"
@app.errorhandler(503)
def error_503(error):
return render_template("maintenance.html")
Related Topics
Openpyxl 1.8.5: Reading the Result of a Formula Typed in a Cell Using Openpyxl
Python CSV.Reader: How to Return to the Top of the File
Python Pack() and Grid() Methods Together
Python | Accessing Dll Using Ctypes
Attributeerror: 'List' Object Has No Attribute 'Click' - Selenium Webdriver
Seeking from End of File Throwing Unsupported Exception
How to "Zip Sort" Parallel Numpy Arrays
Convert Alphabet Letters to Number in Python
Install MySQL-Python (Windows)
Python: Sort Function Breaks in the Presence of Nan
Region: Ioerror: [Errno 22] Invalid Mode ('W') or Filename
Integer Overflow in Numpy Arrays
Convert Bytes to Bits in Python
Use Python Requests to Download CSV