Search code examples
pythonurlflaskintrospection

Flask: Get URLs for each View class in module


I'm trying to build a list of all urls and their respective View or MethodView classes. Each View may have 2 or more urls. I'm not sure whether to do this by starting at the class end, or the url map. My problem with starting with the class is that url_for only returns one url and the endpoint name could possibly be different to the class/method name. This is for building api documentation which seems to be keyed to the url (for end users).

Example:

app = flask.Flask(__name__)

class Bar(View):

    def dispatch_request(self):
        pass
app.add_url_rule('/short/', view_func=Bar.as_view('bar'))
app.add_url_rule('/short/<bar>/', view_func=Bar.as_view('bar'))


if __name__ == '__main__':
    app.run()

The aim here is to be able to perform introspection on the module and get back a list Views all urls that are redirected to that View class or function.


Solution

  • I wonder if something like:

    rules = app.url_map._rules
    for rule in rules:
        print rule.endpoint, rule, rule.defaults
    

    Would get you the information you need. You can read up more on it in the Werkzeug documentation.