How to find all registered URLs in a Flask application
Published on Aug. 22, 2023, 12:16 p.m.
To find all registered URLs in a Flask application, you can import the url_map
object from the Flask instance and loop through its rules
attribute. Here’s an example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/about')
def about():
return 'About page'
if __name__ == '__main__':
with app.test_request_context():
for rule in app.url_map.iter_rules():
print(rule)
In this example, we define a Flask application with two routes - '/'
and '/about'
- each mapping to a different view function.
When we run the application, Flask will automatically generate a URL map, which we can access through the url_map
attribute of the app instance. We can then loop through the rules
attribute of that map to print out each URL route.
Note that we are using the test_request_context()
method to set up a temporary request context, which is required to access the url_map
object in this way.