我有一个复杂的基于Flask的网络应用程序.有许多带视图功能的独立文件.他们的URL是用@app.route('/...')装饰器定义的.有没有办法获得在我的应用程序中声明的所有路线的列表?也许有一些方法我可以调用这个app对象?
Sea*_*ira 135
应用程序的所有路由都存储在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
Run Code Online (Sandbox Code Playgroud)
请参阅显示为创建的新网页的链接以获取更多信息.
小智 63
我刚刚遇到了同样的问题.上述解决方案过于复杂.只需在项目下打开一个新shell:
python
>>> from app import app
>>> app.url_map
Run Code Online (Sandbox Code Playgroud)
第一个' app '是我的项目脚本:app.py,另一个是我的网站名称.
(这个解决方案适用于带有一点路线的细小网页)
Jon*_*han 54
我对我做了一个帮助方法manage.py:
@manager.command
def list_routes():
import urllib
output = []
for rule in app.url_map.iter_rules():
options = {}
for arg in rule.arguments:
options[arg] = "[{0}]".format(arg)
methods = ','.join(rule.methods)
url = url_for(rule.endpoint, **options)
line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url))
output.append(line)
for line in sorted(output):
print line
Run Code Online (Sandbox Code Playgroud)
它通过构建一组虚拟选项来解决缺少的参数.输出如下:
CampaignView:edit HEAD,OPTIONS,GET /account/[account_id]/campaigns/[campaign_id]/edit
CampaignView:get HEAD,OPTIONS,GET /account/[account_id]/campaign/[campaign_id]
CampaignView:new HEAD,OPTIONS,GET /account/[account_id]/new
Run Code Online (Sandbox Code Playgroud)
然后运行它:
python manage.py list_routes
有关manage.py checkout的更多信息,请访问:http://flask-script.readthedocs.org/en/latest/
Joh*_*ang 41
与Jonathan的回答类似,我选择这样做.我没有看到使用url_for的意义,因为如果你的参数不是字符串,例如float,它会破坏
@manager.command
def list_routes():
import urllib
output = []
for rule in app.url_map.iter_rules():
methods = ','.join(rule.methods)
line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, rule))
output.append(line)
for line in sorted(output):
print(line)
Run Code Online (Sandbox Code Playgroud)
the*_*man 21
显然,从版本0.11开始,Flask有一个内置的CLI.其中一个内置命令列出了路由:
FLASK_APP='my_project.app' flask routes
Run Code Online (Sandbox Code Playgroud)
小智 7
由于您没有指定它必须在命令行中运行,因此可以轻松地在 json 中为仪表板或其他非命令行界面返回以下内容。无论如何,从设计的角度来看,结果和输出真的不应该混在一起。这是糟糕的程序设计,即使它是一个很小的程序。然后可以在 Web 应用程序、命令行或任何其他摄取 json 的内容中使用下面的结果。
您也没有指定您需要知道与每条路线关联的 python 函数,因此这更准确地回答了您的原始问题。
我在下面使用自己将输出添加到监控仪表板。如果您想要可用的路由方法(GET、POST、PUT 等),则需要将其与上述其他答案结合起来。
Rule 的repr () 负责转换路由中所需的参数。
def list_routes():
routes = []
for rule in app.url_map.iter_rules():
routes.append('%s' % rule)
return routes
Run Code Online (Sandbox Code Playgroud)
使用列表理解同样的事情:
def list_routes():
return ['%s' % rule for rule in app.url_map.iter_rules()]
Run Code Online (Sandbox Code Playgroud)
示例输出:
{
"routes": [
"/endpoint1",
"/nested/service/endpoint2",
"/favicon.ico",
"/static/<path:filename>"
]
}
Run Code Online (Sandbox Code Playgroud)
如果您需要访问视图函数本身,请app.url_map使用代替app.view_functions。
示例脚本:
from flask import Flask
app = Flask(__name__)
@app.route('/foo/bar')
def route1():
pass
@app.route('/qux/baz')
def route2():
pass
for name, func in app.view_functions.items():
print(name)
print(func)
print()
Run Code Online (Sandbox Code Playgroud)
运行上面脚本的输出:
static
<bound method _PackageBoundObject.send_static_file of <Flask '__main__'>>
route1
<function route1 at 0x128f1b9d8>
route2
<function route2 at 0x128f1ba60>
Run Code Online (Sandbox Code Playgroud)
(请注意包含“静态”路由,它是由 Flask 自动创建的。)
| 归档时间: |
|
| 查看次数: |
56079 次 |
| 最近记录: |