什么是Flask中的“端点”? [英] What is an 'endpoint' in Flask?

查看:159
本文介绍了什么是Flask中的“端点”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask文档显示

  add_url_rule(* args,** kwargs)
连接URL规则。工作完全像路由()装饰。
如果提供了view_func,它将被注册到端点。

端点 - 注册的URL规则的端点。 Flask本身将视图函数的名称视为端点

终点是什么意思? Flask的整个想法和底层的Werkzeug库)将URL路径映射到您将运行的一些逻辑(通常是视图函数)。您的基本视图是这样定义的:

$ $ $ $ $ c $ @ app.route('/ greeting /< name>')
def give_greeting(name):
return'Hello,{0}!'。format(name)

请注意,您引用的函数(add_url_rule)达到了相同的目标,只是不使用装饰符号。因此,以下是相同的:

 #这里没有路由装饰器。我们将使用下面的不同方法添加路由。 
def give_greeting(name):
return'Hello,{0}!'。format(name)

app.add_url_rule('/ greeting /< name> 'give_greeting',give_greeting)

假设您的网站位于www.example.org使用上述观点。用户在浏览器中输入以下URL:

  http://www.example.org/greeting/Mark 

Flask的工作是获取这个URL,找出用户想要做什么,然后传递给你的许多python函数之一处理。它需要路径

  / greeting / Mark 

...并将其匹配到路线列表。在我们的例子中,我们定义了这个路径去 give_greeting 函数。

然而,虽然这是典型的你可能会创建一个视图的方式,它实际上抽象了一些额外的信息。在幕后,Flask并没有直接从URL到应该处理这个请求的视图函数。它不是简单地说...

  URL(http://www.example.org/greeting/Mark)应该是通过View Function(函数my_greeting)来处理它实际上还有另外一个步骤,将URL映射到一个端点:

  URL(http://www.example.org/greeting/Mark)应该被处理由端点my_greeting。 
端点my_greeting的请求应该由View Functionmy_greeting处理

基本上, 端点是用于确定代码的逻辑单元应该处理请求的标识符。通常情况下,端点只是一个视图函数的名称。但是,实际上可以更改端点,如以下示例所示。

  @ app.route('/ greeting / < name>,endpoint ='say_hello')
def give_greeting(name):
return'Hello,{0}!'。format(name)

现在,当Flask路由请求时,逻辑如下所示:

  URL(http://www.example.org/greeting/Mark)应由Endpointsay_hello处理。 
应该由View Functionmy_greeting处理Endpointsay_hello



如何使用端点



端点通常用于反向查找。例如,在您的Flask应用程序的一个视图中,您想要引用另一个视图(也许当您从站点的一个区域链接到另一个区域时)。您可以使用 url_for()来代替对网址进行硬编码, 。假设如下:

  @ app.route('/')
def index():
print url_for('give_greeting',name ='Mark')#这将打印'/ greeting / Mark'

@ app.route('/ greeting /< name>')
def格式(名称)



<
返回'Hello,{0}!'这是有利的,因为现在我们可以改变我们的应用程序的URL,而不需要改变我们引用该资源的行。



为什么不总是使用名字的视图函数?$ / b
$ b

可能出现的一个问题是:为什么我们需要这个额外的层?为什么要将路径映射到端点,然后将端点映射到视图函数?为什么不跳过中间步骤?



原因是因为这种方法更强大。例如, Flask Blueprints 允许您将应用程序分成不同的部分。我可能将所有管理端资源放在名为admin的蓝图中,并将端点中的所有用户级资源都称为用户。

蓝图允许你将它们分离到命名空间中。例如... ...

main.py:

pre $ 从烧瓶导入Flask,Blueprint
from admin import admin
从用户导入用户

app = Flask(__ name__)
app.register_blueprint(admin,url_prefix ='admin')
app.register_blueprint(user,url_prefix ='user')

admin.py:

  admin =蓝图('admin',__name__)

@ admin.route('/ greeting' )
def greeting():
return'Hello,administrative user!'

user.py:

  user = Blueprint('user',__name__)
@ user.route('/ ())
def greeting():
return'Hello,lowly normal user!'

请注意,在这两个蓝图中,/ greeting路由是一个名为greeting的函数。如果我想引用管理问候功能,我不能只是说问候,因为也有用户问候功能。端点允许您将蓝图的名称指定为端点的一部分,从而实现一种命名空间。所以,我可以做以下...

 打印url_for('admin.greeting')#打印'/ admin / greeting '
print url_for('user.greeting')#打印'/ user / greeting'


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"?

解决方案

How Flask Routing Works

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:

@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:

# 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:

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:

/greeting/Mark

...and matches it to the list of routes. In our case, we defined this path to go to the give_greeting function.

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...

URL (http://www.example.org/greeting/Mark) should be handled by View Function (the function "my_greeting")

Actually, it there is another step, where it maps the URL to an endpoint:

URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "my_greeting".
Requests to Endpoint "my_greeting" should be handled by View Function "my_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:

URL (http://www.example.org/greeting/Mark) should be handled by Endpoint "say_hello".
Endpoint "say_hello" should be handled by View Function "my_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

@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.

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 Blueprints allow 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".

Blueprints allow you to separate these into namespaces. For example...

main.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:

admin = Blueprint('admin', __name__)

@admin.route('/greeting')
def greeting():
    return 'Hello, administrative user!'

user.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...

print url_for('admin.greeting') # Prints '/admin/greeting'
print url_for('user.greeting') # Prints '/user/greeting'

这篇关于什么是Flask中的“端点”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆