如何获取网页上的Flask应用路由列表

How to get a list of Flask application routes on a webpage

我有一个用 Python3.6.x 编写的烧瓶应用程序,它位于 docker.

当我有后端的 docker 容器和 运行 时,我可以做 FLASK_APP='run.py' flask routes 以获取 shell.

内应用程序中所有端点的列表

我应该做哪些更改才能将整个列表作为 web/html 页面??

What changes should I make to get that entire list as a web/html page??

我猜你希望 flask routes 的输出在你自己的路由中可用,这样你就可以通过将它传递给模板或其他东西来渲染它...

查看 flask routes command is implemented 的位置以及它如何抓取数据...

def routes_command(sort: str, all_methods: bool) -> None:
    """Show all registered routes with endpoints and methods."""

    rules = list(current_app.url_map.iter_rules())
    if not rules:
        click.echo("No routes were registered.")
        return

所以要在您自己的程序中实现它,您可以这样做:

from flask import Flask, current_app

app = Flask(__name__)

# Just another demonstration route for the output.
@app.route('/some/route/<withParam>')
def some_route(withParam): return 'success'

@app.route('/')
def index():
    rules = list(current_app.url_map.iter_rules())
    
    if not rules: 
        return 'No rules defined'

    def get_dict(rule):
        return { 'endpoint': rule.endpoint,
                 'methods': ','.join(rule.methods),
                 'rule': rule.rule }

    output_list = [get_dict(r) for r in rules]

    print (output_list)

    return 'success'

output_list 是字典列表,如下所示:

[{'endpoint': 'index',
  'methods': 'GET,HEAD,OPTIONS',
  'rule': '/'},

 {'endpoint': 'some_route',
  'methods': 'GET,HEAD,OPTIONS',
  'rule': '/some/route/<withParam>'},

 {'endpoint': 'static',
  'methods': 'GET,HEAD,OPTIONS',
  'rule': '/static/<path:filename>'}]

显然在上面的示例中我只是将它打印到终端,但是现在你在 python 数据结构中有了它,很容易通过 render_template 传递它并显示它在页面中。