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?
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.
Basically, the "endpoint" is an identifier that is used in determining what logical unit of your code should handle the request. Normally, an endpoint is just the name of a view function. However, you can actually change the endpoint, as is done in the following example.
Endpoints Frameworks for Python is integrated with the App Engine standard Python 2.7 runtime environment. Endpoints Frameworks consists of tools, libraries, and capabilities that let you generate APIs and client libraries from an App Engine application.
So first make sure you have pipenv running, and then say python app.py . I'm not getting any errors so that's a good sign. And then this is going to be a POST request. Our goal is to create a new guide and then we need to pass the data in.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With