简体   繁体   中英

What is the "endpoint" parameter for @app.route() used for?

In Flask, you create routes like this:

from flask import Flask

app = Flask(__name__)

@app.route("/foobar")
def foo_bar_endpoint():
    ...

But the route decorator also has an endpoint parameter. The documentation just states:

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

Why should / would one not simply name the function as the endpoint should be called? Is this relevant for anything else than url_for ?

The "endpoint" is an arbitrary name you provide, which is basically the canonical thing that a route refers to. You're not actually mapping a URL to a function there, you're mapping a URL to an endpoint and are attaching a view function to that endpoint.

URL → endpoint → function

You're just doing all that in one action, and the name of the function automatically becomes the name of the endpoint in the process. But you could do this all separately and register an endpoint for a URL, and later attach a function to that endpoint:

Basically this example:

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

Is equivalent to the following:

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

If the view_func is not provided you will need to connect the endpoint to a view function like so:

 app.view_functions['index'] = index

https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.add_url_rule

You may want to name your endpoint independently of your function, if you're under some constraint for the function name but are already referring to the endpoint from elsewhere, especially during refactoring, as one possible example where that might become relevant.

The URL is for external clients, for HTTP-requests.

The endpoint is for internal usage if you need to know which URL to redirect for example without any hardcoding.

In case you not defining endpoint your code looks like:

blueprint = Blueprint("bp_1", __name__)


@blueprint.route("/foobar")
def foo_bar_endpoint():
    ...


url = flask.url_for("bp_1.foo_bar_endpoint")

In case you define endpoint, you use function url_for with its name:

@blueprint.route("/foobar", endpoint="custom_name")
def foo_bar_endpoint():
    ...


url = flask.url_for("bp_1. custom_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