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 的介绍这里就不多说了,可以直接去官网查看. 关于这个单页面应用 ...
随机推荐
- Java如何操作对象(bean)进行动态排序?
原文出自:https://blog.csdn.net/seesun2012 简介如题:Java如何操作对象(bean)进行动态排序?Java实体类(bean)动态排序? 原理:利用反射根据指定的属性值 ...
- c#之泛型详解(Generic)
这篇文章主要来讲讲c#中的泛型,因为泛型在c#中有很重要的位置,对于写出高可读性,高性能的代码有着关键的作用. 一.什么是泛型? 泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个非 ...
- K:顺序表和链表的比较
顺序表和链表是线性表的两种基本实现形式(链表还有多种变化形式),对于这两种实现方式,没有一种方法可以称是最好的,他们各自有着各自的特点和优缺点,适用于不同的应用场景. 与顺序表相比,链表较为灵活, ...
- js-js的全局变量和局部变量
*** 全局变量:在script标签里面定义一个变量,这个变量在页面中js部分都可以使用 - 在方法外部使用,在方法内部使用,在另外一个script标签中使用 *** 局部变量:在方法内部定义一个变量 ...
- [SDOI2014]旅行解题报告
题目描述 S国有N个城市,编号从1到N.城市间用N-1条双向道路连接,满足从一个城市出发可以到达其它所有城市.每个城市信仰不同的宗教,如飞天面条神教.隐形独角兽教.绝地教都是常见的信仰. 为了方便,我 ...
- C语言——二叉排序树
二叉排序树是一种实现动态查找的树表,又称二叉查找树. 二叉排序树的性质: 1. 若它的左子树不为空,则左子树上所有节点的键值均小于它的根节点键值 2. 若它的右子树不为空,则右子树上所有节点的键值均大 ...
- Activiti 数据库表自动生成策略
Activiti 引擎启动时默认会检测数据库版本与程序版本是否相符,不相符就会抛出异常停止引擎的初始化. 这一策略可以通过引擎的初始化配置参数databaseSchemaUpdate来控制, 如下图的 ...
- 一键清理 Nexus 中无用的 Docker 镜像
现许多团队使用 Nexus 来管理 Docker 镜像,产品不断迭代,镜像仓库占用的磁盘空间也越来越大.由于 Nexus 的控制台并未提供批量操作镜像功能,清理镜像十分不便.本文分享一个清理 Nexu ...
- php中http_build_query函数
http_build_query ( array $formdata [, string $numeric_prefix ] ) 使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求 ...
- Volley框架实现Http的get和post请求
一: volley简介: Google I/O 2013上,Volley发布了.Volley是Android平台上的网络通信库,能使网络通信更快,更简单,更健壮.这是Volley名称的由来: a bu ...