@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
# Then to run it:
# `python manage.py list_routes`
@admin_api.route('/help', methods=['GET'])
def routes_info():
"""Print all defined routes and their endpoint docstrings
This also handles flask-router, which uses a centralized scheme
to deal with routes, instead of defining them as a decorator
on the target function.
"""
routes = []
for rule in app.url_map.iter_rules():
try:
if rule.endpoint != 'static':
if hasattr(app.view_functions[rule.endpoint], 'import_name'):
import_name = app.view_functions[rule.endpoint].import_name
obj = import_string(import_name)
routes.append({rule.rule: "%s\n%s" % (",".join(list(rule.methods)), obj.__doc__)})
else:
routes.append({rule.rule: app.view_functions[rule.endpoint].__doc__})
except Exception as exc:
routes.append({rule.rule:
"(%s) INVALID ROUTE DEFINITION!!!" % rule.endpoint})
route_info = "%s => %s" % (rule.rule, rule.endpoint)
app.logger.error("Invalid route: %s" % route_info, exc_info=True)
# func_list[rule.rule] = obj.__doc__
return jsonify(code=200, data=routes)
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods = ['GET'])
def this_func():
"""This is a function. It does nothing."""
return jsonify({ 'result': '' })
@app.route('/api/help', methods = ['GET'])
def help():
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list)
if __name__ == '__main__':
app.run(debug=True)
# ONE MORE VARIANT
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