How does Flask url_for work?

后端 未结 1 619
既然无缘
既然无缘 2020-12-12 03:45
flask.url_for(endpoint, **values)

The endpoint thing seems like magic to me. It behaves these ways:

  1. in a single file, a
相关标签:
1条回答
  • 2020-12-12 04:32

    Flask does not use the module name for the endpoint. It simply defaults to the function name.

    If you register two different functions with the same name (say, in two different modules), an AssertionError exception is raised:

    raise AssertionError('View function mapping is overwriting an '
                         'existing endpoint function: %s' % endpoint)
    

    You can specify an explicit endpoint name in such cases:

    @app.route('/', endpoint='alt_homepage')
    def homepage():
        pass
    

    See the @Flask.route() documentation:

    endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

    When you register a view (with the @app.route() decorator), the endpoint name is determined (unless you set one explicitly) and stored with the route registration. url_for() uses the route registration to find all routes registered against that name and finds the one best fitting the parameters you also passed to url_for().

    0 讨论(0)
提交回复
热议问题