深度阅读

How to find all registered URLs in a Flask application

作者
作者
2023年08月22日
更新时间
10.18 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。