Python Flask 中的“端点”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19261833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is an 'endpoint' in Flask?
提问by Fuziang
The Flask documentation shows:
该瓶文档显示:
add_url_rule(*args, **kwargs)
Connects a URL rule. Works exactly like the route() decorator.
If a view_func is provided it will be registered with the endpoint.
endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint
What exactly is meant by an "endpoint"?
“端点”究竟是什么意思?
采纳答案by Mark Hildreth
How Flask Routing Works
Flask 路由是如何工作的
The entire idea of Flask (and the underlying Werkzeug library) is to map URL paths to some logic that you will run (typically, the "view function"). Your basic view is defined like this:
Flask(以及底层的 Werkzeug 库)的整个想法是将 URL 路径映射到您将运行的某些逻辑(通常是“视图函数”)。您的基本视图定义如下:
@app.route('/greeting/<name>')
def give_greeting(name):
return 'Hello, {0}!'.format(name)
Note that the function you referred to (add_url_rule) achieves the same goal, just without using the decorator notation. Therefore, the following is the same:
请注意,您引用的函数 (add_url_rule) 实现了相同的目标,只是不使用装饰器符号。因此,以下内容相同:
# No "route" decorator here. We will add routing using a different method below.
def give_greeting(name):
return 'Hello, {0}!'.format(name)
app.add_url_rule('/greeting/<name>', 'give_greeting', give_greeting)
Let's say your website is located at 'www.example.org' and uses the above view. The user enters the following URL into their browser:
假设您的网站位于“www.example.org”并使用上述视图。用户在浏览器中输入以下 URL:
http://www.example.org/greeting/Mark
The job of Flask is to take this URL, figure out what the user wants to do, and pass it on to one of your many python functions for handling. It takes the path:
Flask 的工作是获取这个 URL,弄清楚用户想要做什么,然后将它传递给许多 Python 函数之一进行处理。它需要路径:
/greeting/Mark
...and matches it to the list of routes. In our case, we defined this path to go to the give_greeting
function.
...并将其与路线列表相匹配。在我们的例子中,我们定义了这个路径去到give_greeting
函数。
However, while this is the typical way that you might go about creating a view, it actually abstracts some extra info from you. Behind the scenes, Flask did not make the leap directly from URL to the view function that should handle this request. It does not simply say...
然而,虽然这是您创建视图的典型方式,但它实际上从您那里抽象了一些额外的信息。在幕后,Flask 并没有直接从 URL 跳转到应该处理这个请求的视图函数。不是简单的说...
URL (http://www.example.org/greeting/Mark) should be handled by View Function (the function "give_greeting")
Actually, it there is another step, where it maps the URL to an endpoint:
实际上,还有另一个步骤,它将 URL 映射到端点:
URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "give_greeting".
Requests to Endpoint "give_greeting" should be handled by View Function "give_greeting"
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.
基本上,“端点”是一个标识符,用于确定代码的哪个逻辑单元应该处理请求。通常,端点只是视图函数的名称。但是,您实际上可以更改端点,如下例所示。
@app.route('/greeting/<name>', endpoint='say_hello')
def give_greeting(name):
return 'Hello, {0}!'.format(name)
Now, when Flask routes the request, the logic looks like this:
现在,当 Flask 路由请求时,逻辑如下所示:
URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "say_hello".
Endpoint "say_hello" should be handled by View Function "give_greeting"
How You Use the Endpoint
您如何使用端点
The endpoint is commonly used for the "reverse lookup". For example, in one view of your Flask application, you want to reference another view (perhaps when you are linking from one area of the site to another). Rather than hard-code the URL, you can use url_for()
. Assume the following
端点通常用于“反向查找”。例如,在 Flask 应用程序的一个视图中,您想要引用另一个视图(也许当您从站点的一个区域链接到另一个区域时)。您可以使用url_for()
. 假设以下
@app.route('/')
def index():
print url_for('give_greeting', name='Mark') # This will print '/greeting/Mark'
@app.route('/greeting/<name>')
def give_greeting(name):
return 'Hello, {0}!'.format(name)
This is advantageous, as now we can change the URLs of our application without needing to change the line where we reference that resource.
这是有利的,因为现在我们可以更改应用程序的 URL,而无需更改引用该资源的行。
Why not just always use the name of the view function?
为什么不总是使用视图函数的名称?
One question that might come up is the following: "Why do we need this extra layer?" Why map a path to an endpoint, then an endpoint to a view function? Why not just skip that middle step?
一个可能会出现的问题是:“为什么我们需要这个额外的层?” 为什么将路径映射到端点,然后将端点映射到视图函数?为什么不跳过中间步骤呢?
The reason is because it is more powerful this way. For example, Flask Blueprintsallow you to split your application into various parts. I might have all of my admin-side resources in a blueprint called "admin", and all of my user-level resources in an endpoint called "user".
原因是因为这种方式更强大。例如,Flask 蓝图允许您将应用程序拆分为不同的部分。我可能在名为“admin”的蓝图中拥有我的所有管理端资源,而在名为“user”的端点中拥有我的所有用户级资源。
Blueprints allow you to separate these into namespaces. For example...
蓝图允许您将它们分成命名空间。例如...
main.py:
主要.py:
from flask import Flask, Blueprint
from admin import admin
from user import user
app = Flask(__name__)
app.register_blueprint(admin, url_prefix='admin')
app.register_blueprint(user, url_prefix='user')
admin.py:
管理.py:
admin = Blueprint('admin', __name__)
@admin.route('/greeting')
def greeting():
return 'Hello, administrative user!'
user.py:
用户.py:
user = Blueprint('user', __name__)
@user.route('/greeting')
def greeting():
return 'Hello, lowly normal user!'
Note that in both blueprints, the '/greeting' route is a function called "greeting". If I wanted to refer to the admin "greeting" function, I couldn't just say "greeting" because there is also a user "greeting" function. Endpoints allow for a sort of namespacing by having you specify the name of the blueprint as part of the endpoint. So, I could do the following...
请注意,在两个蓝图中,'/greeting' 路由是一个称为“greeting”的函数。如果我想提到管理“问候”功能,我不能只说“问候”,因为还有一个用户“问候”功能。通过让您将蓝图的名称指定为端点的一部分,端点允许某种命名空间。所以,我可以做以下...
print url_for('admin.greeting') # Prints '/admin/greeting'
print url_for('user.greeting') # Prints '/user/greeting'
回答by plaes
Endpoint is the name used to reverse-lookup the url rules with url_for
and it defaults to the name of the view function.
Endpoint 是用于反向查找 url 规则url_for
的名称,它默认为视图函数的名称。
Small example:
小例子:
from flask import Flask, url_for
app = Flask(__name__)
# We can use url_for('foo_view') for reverse-lookups in templates or view functions
@app.route('/foo')
def foo_view():
pass
# We now specify the custom endpoint named 'bufar'. url_for('bar_view') will fail!
@app.route('/bar', endpoint='bufar')
def bar_view():
pass
with app.test_request_context('/'):
print url_for('foo_view')
print url_for('bufar')
# url_for('bar_view') will raise werkzeug.routing.BuildError
print url_for('bar_view')