loading...

Flask: list of routes

rhymes profile image rhymes Updated on ・1 min read

Update: starting from Flask 1.0 there's a builtin flask routes command

One of the cool things about Rails is rails routes (ex rake routes) which shows on the console the list of routes registered to an application.

I have a Flask application made of different views and blueprints which as it becomes larger and more complex makes it hard to remember all the registered routes.

I googled for "flask list of routes" and ended up on an old snippet which breaks in the latest Flask versions.

This is a working version:

@app.cli.command()
def routes():
    'Display registered routes'
    rules = []
    for rule in app.url_map.iter_rules():
        methods = ','.join(sorted(rule.methods))
        rules.append((rule.endpoint, methods, str(rule)))

    sort_by_rule = operator.itemgetter(2)
    for endpoint, methods, rule in sorted(rules, key=sort_by_rule):
        route = '{:50s} {:25s} {}'.format(endpoint, methods, rule)
        print(route)
  • @app.cli.command() tells Flask cli to register the command routes
  • The line sort_by_rule = operator.itemgetter(2) is used to create a function (used in the following line to sort) that extracts the item in position number 2 in a list. This way Python sorts the results by that item.

This is an example of result:

$ flask routes
frontend.index                                     GET,HEAD,OPTIONS          /
frontend.index                                     GET,HEAD,OPTIONS          /<path:path>
admin.index                                        GET,HEAD,OPTIONS          /admin/
product.index_view                                 GET,HEAD,OPTIONS          /admin/product/
api.products_show                                  GET,HEAD,OPTIONS          /api/v1/products/<string:product_id>
rq_dashboard.overview                              GET,HEAD,OPTIONS          /jobs/
frontend.static                                    GET,HEAD,OPTIONS          /static/<path:filename>

Posted on May 28 by:

rhymes profile

rhymes

@rhymes

Software developer @ DEV

Discussion

markdown guide
 

+1 for "operator.itemgetter(2)" - how did I never know that? :)