简体   繁体   中英

What is the “endpoint” in flask's .add_url_rule()?

Consider the following code

import flask

class API:
    def hello(self):
        return flask.Response('hello', 200)

api = API()
app = flask.Flask(__name__)
app.add_url_rule('/', 'hello', api.hello)
app.run()

It returns "hello" upon a GET call to / .

The documentation for add_url_rule states that

[ add_url_rule ] works exactly like the route() decorator.

It requires however at least three parameters. The first and third one are understandable and mimic @route() . What is the second one ( hello in my case)?

The documentation further states that this is

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

What does this mean? Why isn't the URL ( / ) and the method to call ( api.hello ) sufficient? What is the role of the "endpoint"? How is it exactly used?

It's the name for the route; the one you'd use in the url_for() function for example. The endpoint name is the registration key for views, a symbolic name by which you can reference the route from other parts of your application.

@route() takes the same parameter; the default is the name of the decorated function. This is documented both in the add_url_rule() documentation as well as the documentation for @route() :

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

(bold italic emphasis mine).

Note that the example in the documentation tried to show the same:

Basically this example:

 @app.route('/') def index(): pass 

Is equivalent to the following:

 def index(): pass app.add_url_rule('/', 'index', index) 

Note that the second argument 'index' matches the function name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM