我有一个复杂的基于Flask的Web应用程序。有许多具有视图功能的单独文件。它们的URL由@app.route('/...')装饰器定义。有没有办法获取我的应用中已声明的所有路线的列表?也许有一些我可以调用该app对象的方法?
@app.route('/...')
app
应用程序的所有路由都存储在app.url_map的实例上werkzeug.routing.Map。你可以Rule使用以下iter_rules方法遍历实例:
app.url_map
werkzeug.routing.Map
Rule
iter_rules
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