获取在 Flask 应用程序中定义的所有路由的列表 [英] Get list of all routes defined in the Flask app
问题描述
我有一个复杂的基于 Flask 的网络应用程序.有很多带有视图功能的单独文件.它们的 URL 是用 @app.route('/...')
装饰器定义的.有没有办法获取在我的应用程序中声明的所有路由的列表?也许我可以在 app
对象上调用一些方法?
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?
推荐答案
一个应用程序的所有路由都存储在 app.url_map
这是 werkzeug.routing.Map
.您可以遍历 Rule
实例通过使用 iter_rules
方法:
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
请参阅显示指向创建的新网页的链接更多信息.
这篇关于获取在 Flask 应用程序中定义的所有路由的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!