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:36

You can view all the Routes via flask shell by running the following commands after exporting or setting FLASK_APP environment variable. flask shell app.url_map

查看更多
【Aperson】
3楼-- · 2020-01-24 19:41

Since you did not specify that it has to be run command-line, the following could easily be returned in json for a dashboard or other non-command-line interface. The result and the output really shouldn't be commingled from a design perspective anyhow. It's bad program design, even if it is a tiny program. The result below could then be used in a web application, command-line, or anything else that ingests json.

You also didn't specify that you needed to know the python function associated with each route, so this more precisely answers your original question.

I use below to add the output to a monitoring dashboard myself. If you want the available route methods (GET, POST, PUT, etc.), you would need to combine it with other answers above.

Rule's repr() takes care of converting the required arguments in the route.

def list_routes():
    routes = []

    for rule in app.url_map.iter_rules():
        routes.append('%s' % rule)

    return routes

The same thing using a list comprehension:

def list_routes():
    return ['%s' % rule for rule in app.url_map.iter_rules()]

Sample output:

{
  "routes": [
    "/endpoint1", 
    "/nested/service/endpoint2", 
    "/favicon.ico", 
    "/static/<path:filename>"
  ]
}
查看更多
淡お忘
4楼-- · 2020-01-24 19:42

I make a helper method on my 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

It solves the the missing argument by building a dummy set of options. The output looks like:

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

Then to run it:

python manage.py list_routes

For more on manage.py checkout: http://flask-script.readthedocs.org/en/latest/

查看更多
登录 后发表回答