Issue
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 theroute()
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?
Solution
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.
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.