Home > Mobile >  How to get a list of Flask application routes on a webpage
How to get a list of Flask application routes on a webpage

Time:01-06

I have a flask application written in Python3.6.x that lives in a docker.

When I have the docker container for the backend up and running, I can do FLASK_APP='run.py' flask routes to get a list of all the endpoints in the application within the shell.

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

CodePudding user response:

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

I'm guessing you want the output of flask routes available within a your own route, so you can then render this, by passing it to a template or something...

See where the flask routes command is implemented and how this grabs the data...

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

So to implement this in your own program, you could do the same:

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 is a list of dictionaries which looks like:

[{'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>'}]

Obviously in the above sample I've just printed this to the terminal, but now that you have this in a python data structure, it's easy enough to pass this via render_template and display it in page.

  •  Tags:  
  • Related