博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How Flask Routing Works
阅读量:4309 次
发布时间:2019-06-06

本文共 5023 字,大约阅读时间需要 16 分钟。

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/
')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:

def give_greeting(name):    return 'Hello, {0}!'.format(name)app.add_url_rule('/greeting/
', '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/
', 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 . Assume the following

@app.route('/')def index():    print url_for('give_greeting', name='Mark') # This will print '/greeting/Mark'@app.route('/greeting/
')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 skip?

The reason is because it is more powerful this way. For example, 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, Blueprintfrom admin import adminfrom user import userapp = 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'

Small example:

from flask import Flask, url_forapp = 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():    passwith 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')

转载于:https://www.cnblogs.com/liunnis/p/4639379.html

你可能感兴趣的文章
基于注解的SpringMVC
查看>>
Html+Css实现九大行星动画效果
查看>>
【20190405】JavaScript-整理一些常用正则式
查看>>
git 常用命令
查看>>
【光影魔术手】简单使用
查看>>
关于sqoop与datax。 和sqoop to oracle插件OraOop
查看>>
国内其他的maven库
查看>>
关于 控制反转与依赖注入 对初学者的一点帮助
查看>>
MySQL学习笔记(一)Ubuntu16.04中MySQL安装配置(5.6优化、错误日志、DNS解决)
查看>>
解决NLPIR汉语分词系统init failed问题
查看>>
袖珍C库
查看>>
深入理解JavaScript系列(10):JavaScript核心(晋级高手必读篇)
查看>>
Angularjs演示Service功能
查看>>
Unable to launch the IIS Express Web server
查看>>
黑客与画家 第七章
查看>>
Tomcat实践
查看>>
第二次冲刺计划周第四天
查看>>
leetcode 120. Triangle
查看>>
边缘网关协议(BGP)
查看>>
github和gitlab并存
查看>>