I have a complex Flask-based web app. There are lots of separate files with view functions. Their URLs are defined with the @app.route('/...')
decorator. Is there a way to get a list of all the routes that have been declared throughout my app? Perhaps there is some method I can call on the app
object?
Advertisement
Answer
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:
JavaScript
x
21
21
1
from flask import Flask, url_for
2
3
app = Flask(__name__)
4
5
def has_no_empty_params(rule):
6
defaults = rule.defaults if rule.defaults is not None else ()
7
arguments = rule.arguments if rule.arguments is not None else ()
8
return len(defaults) >= len(arguments)
9
10
11
@app.route("/site-map")
12
def site_map():
13
links = []
14
for rule in app.url_map.iter_rules():
15
# Filter out rules we can't navigate to in a browser
16
# and rules that require parameters
17
if "GET" in rule.methods and has_no_empty_params(rule):
18
url = url_for(rule.endpoint, **(rule.defaults or {}))
19
links.append((url, rule.endpoint))
20
# links is now a list of url, endpoint tuples
21
See Display links to new webpages created for a bit more information.