How Flask Routing Works
@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:
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 skip?
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'
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')
How Flask Routing Works的更多相关文章
- 欢迎来到 Flask 的世界
欢迎来到 Flask 的世界 欢迎阅读 Flask 的文档.本文档分成几个部分,我推荐您先读 < 安装 >,然后读< 快速上手 >.< 教程 > 比快速上手文档更详 ...
- IIS URL Rewriting and ASP.NET Routing
IIS URL Rewriting and ASP.NET Routing With the release of the URL Rewrite Module for IIS and the inc ...
- 【转】Controllers and Routers in ASP.NET MVC 3
Controllers and Routers in ASP.NET MVC 3 ambilykk, 3 May 2011 CPOL 4.79 (23 votes) Rate: vote 1vote ...
- The main concepts
The MVC application model A Play application follows the MVC architectural pattern applied to the we ...
- [引]ASP.NET MVC 4 Content Map
本文转自:http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspx The Model-View-Controller (MVC) ...
- webpacke踩坑-新手
1.题叶-webpack入门指南 2.webpack入门系列 3.w3ctech的webpack入门及实践 4.Express结合Webpack的全栈自动刷新 5.webpack 单页面应用实战 6. ...
- python content list(1--4)
part 1 python language 1. environment building and config 2. variable and data type 3. programming b ...
- [转]Web API OData V4 Keys, Composite Keys and Functions Part 11
本文转自:https://damienbod.com/2014/09/12/web-api-odata-v4-keys-composite-keys-and-functions-part-11/ We ...
- webpack 单页面应用实战
这篇文章将介绍如何利用 webpack 进行单页面应用的开发,算是我在实际开发中的一些心得和体会,在这里给大家做一个分享.webpack 的介绍这里就不多说了,可以直接去官网查看. 关于这个单页面应用 ...
随机推荐
- zabbix使用(自定义监控、自动报警)
自定义监控(制作模板) zabbix自带模板Template OS Linux (Template App Zabbix Agent)提供CPU.内存.磁盘.网卡等常规监控,只要新加主机关联此模板,就 ...
- C# XML创建解析、XML格式化
导入命名空间: VS需要在项目中添加引用system.XML; 代码中添加 using System.XML和using System.IO; XML范例: <?xml version=&quo ...
- C# 字符串处理—— 去除首位保留其他
//去除首位 public static string RemoveFirstPlace(string s) { ) //输入空值直接Return { ")) //判断开头是否是零 s = ...
- 远程连接MongoDB数据库
不使用用户名和密码 安装MongoDB后,默认不使用用户名和密码即可在本地登录,如需远程登录,只要修改/bin/mongo.conf文件即可
- Pdf预览功能实现(asp.net)
asp.net中使用 1.pdf预览功能实现的插件是pdfjs-1.5.188-dist //引入插件中相关的文件以及jquery文件 @section css{ <link rel=" ...
- django中的缓存
对于一个动态网站来说,用户的每次访问都意味着对服务器的一次开销,当该服务器的并发访问非常大时,对于一个动态网站来说,开销会非常的大.所以对于大中型web应用来说,减轻服务器的性能瓶颈就很有必要 对于d ...
- Go按照条件编译
Go 支持按照条件编译,具体来说它是通过 go/build包 里定义的tags和命名约定来让Go的包可以管理不同平台的代码 . 我们这里以下面这个开源项目为例,来看Go的按条件编译, 这个开源项目是把 ...
- poj 2796 Feel Good 单调队列
Feel Good Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 8753 Accepted: 2367 Case Ti ...
- Eclipse设置虚拟机参数 (转 构建内存溢出)
Java -verbose:gc 中参数-verbose:gc 表示输出虚拟机中GC的详细情况. 首先在Eclipse的Debug页签中设置虚拟机参数: 步骤: 1.选中已经写好的项目 2.Run-& ...
- git杂记-记录每次更新到仓库
git status 和 git diff的运用 git status 记录的是关于仓库文件是否有变更,例如是否被修改,是否被添加到暂村区.至于文件更改了什么内容该命令并不关心: git status ...