@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的更多相关文章

  1. 欢迎来到 Flask 的世界

    欢迎来到 Flask 的世界 欢迎阅读 Flask 的文档.本文档分成几个部分,我推荐您先读 < 安装 >,然后读< 快速上手 >.< 教程 > 比快速上手文档更详 ...

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

  3. 【转】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 ...

  4. The main concepts

    The MVC application model A Play application follows the MVC architectural pattern applied to the we ...

  5. [引]ASP.NET MVC 4 Content Map

    本文转自:http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspx The Model-View-Controller (MVC) ...

  6. webpacke踩坑-新手

    1.题叶-webpack入门指南 2.webpack入门系列 3.w3ctech的webpack入门及实践 4.Express结合Webpack的全栈自动刷新 5.webpack 单页面应用实战 6. ...

  7. python content list(1--4)

    part 1 python language 1. environment building and config 2. variable and data type 3. programming b ...

  8. [转]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 ...

  9. webpack 单页面应用实战

    这篇文章将介绍如何利用 webpack 进行单页面应用的开发,算是我在实际开发中的一些心得和体会,在这里给大家做一个分享.webpack 的介绍这里就不多说了,可以直接去官网查看. 关于这个单页面应用 ...

随机推荐

  1. linux中find与rm实现查找并删除文件

    find命令: find . -name '*.log' #查找当前目录下的log文件 查找并删除: find . -name '*.log' -type f -print -exec rm -rf ...

  2. Cheatsheet: 2017 07.01 ~ 07.31

    Other 8 Key Application Performance Metrics & How to Measure Them The Code Review: The Most Impo ...

  3. Hadoop源码学习笔记(5) ——回顾DataNode和NameNode的类结构

    Hadoop源码学习笔记(5) ——回顾DataNode和NameNode的类结构 之前我们简要的看过了DataNode的main函数以及整个类的大至,现在结合前面我们研究的线程和RPC,则可以进一步 ...

  4. 一、cent OS安装配置JDK

    到oracle官网下载JDKhttp://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html 在cent OS ...

  5. python用random产生验证码,以及random的一些其他用法

    产生随机验证码函数 import random def get_code(): code = '' for i in range(5): num = str(random.randrange(10)) ...

  6. Spring cloud Zuul网关异常处理

    Spring cloud Zuul网关异常处理 一 异常测试: 1> 创建一个pre类型的过滤器,并在该过滤器的run方法实现中抛出一个异常.比如下面的实现,在run方法中调用的doSometh ...

  7. django框架中form表单Post方法无法提交 Forbidden (403) CSRF verification failed. Request aborted.

    问题如图: 解决方法: 在视图函数中引入并使用装饰器 from django.views.decorators.csrf import csrf_exempt @csrf_exempt

  8. 牛客Wannafly挑战赛23F 计数(循环卷积+拉格朗日插值/单位根反演)

    传送门 直接的想法就是设 \(x^k\) 为边权,矩阵树定理一波后取出 \(x^{nk}\) 的系数即可 也就是求出模 \(x^k\) 意义下的循环卷积的常数项 考虑插值出最后多项式,类比 \(DFT ...

  9. css常见的快捷开发代码汇总(长期更新)

    http://caibaojian.com/popular-css-snippets.html

  10. MySQL数据库(11)----使用子查询实现多表查询

    子查询指的是用括号括起来,并嵌入另一条语句里的那条 SELECT 语句.下面有一个示例,它实现的是找出与考试类别('T')相对应的所有考试事件行的 ID,然后利用它们来查找那些考试的成绩: SELEC ...