Get list of all routes defined in the Flask app

2020-01-24 18:51发布

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?

标签: python flask
9条回答
趁早两清
2楼-- · 2020-01-24 19:24

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

See Display links to new webpages created for a bit more information.

查看更多
走好不送
3楼-- · 2020-01-24 19:28

If you need to access the view functions themselves, then instead of app.url_map, use app.view_functions.

Example script:

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()

Output from running the script above:

static
<bound method _PackageBoundObject.send_static_file of <Flask '__main__'>>

route1
<function route1 at 0x128f1b9d8>

route2
<function route2 at 0x128f1ba60>

(Note the inclusion of the "static" route, which is created automatically by Flask.)

查看更多
Lonely孤独者°
4楼-- · 2020-01-24 19:29

inside your flask app do:

flask shell
>>> app.url_map
Map([<Rule '/' (OPTIONS, HEAD, GET) -> helloworld>,
 <Rule '/static/<filename>' (OPTIONS, HEAD, GET) -> static>])
查看更多
狗以群分
5楼-- · 2020-01-24 19:32

I just met the same question. Those solution above is too complex. Just open a new shell under your project:

    python
    >>> from app import app
    >>> app.url_map

The first 'app' is my project script: app.py, another is my web's name.

(this solution is for tinny web with a little route)

查看更多
够拽才男人
6楼-- · 2020-01-24 19:32

Apparently, since version 0.11, Flask has a built-in CLI. One of the built-in commands lists the routes:

FLASK_APP='my_project.app' flask routes
查看更多
混吃等死
7楼-- · 2020-01-24 19:36

Similar to Jonathan's answer I opted to do this instead. I don't see the point of using url_for as it will break if your arguments are not string e.g. 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)
查看更多
登录 后发表回答