DEV Community


Posted on • Updated on

Flask: list of routes

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:

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)
Enter fullscreen mode Exit fullscreen mode
  • @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>
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

ashuto7h profile image
Ashutosh Sahu

You are a genius. Thanks for this snippet.

ashuto7h profile image
Ashutosh Sahu

By the way, I have added a link to your article in my answer on stackoverflow

rhymes profile image

Thank you!

curtisforrester profile image

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