@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. ayer.prompt 怎样让输入值为空也可以向下执行

    http://fly.layui.com/jie/4227/ layer.prompt({title: '输入任何口令,并确认',formType: 1, //prompt风格,支持0-2value: ...

  2. Grid控件

    Grid控件是WPF布局容器中功能最强大.最灵活的控件.Grid控件基本上能够完成其他WPF容器控件所能完成的功能,Microsoft建议大多数界面的布局都使用Grid控件来实现,因此默认情况下.vs ...

  3. Effective C++ .47 traits与模板特化

    #include <iostream> #include <cstdlib> #include <string> using namespace std; temp ...

  4. curl 模拟发起百度地图API post请求

    注:开始做的是get请求,比较简单,然后又查询了一番就做成了post请求,有几个地方特别说明一下: 一,$address,是必须传的,$city可不传: 二,ak跟之前的key一直,需要申请,我的好像 ...

  5. IE、火狐、谷歌浏览器下兼容统一select样式

    项目开发时,对于不同浏览器下的select样式不统一问题,各种查,这里记录一下,项目已使用 IE浏览器下样式: 火狐浏览器下样式: 谷歌浏览器下样式: 上代码: 1.html 2.css 至此,大功告 ...

  6. WebService程序数据集之WSDL取数

    在通用的webservice集合中,在集合中使用wsdl取数的方式获取数据,并将数据转换为程序数据集,那么怎样通过wsdl取数并转换为程序数据集呢? 首先将wsdl获取到的数据数据转换为二维数组,然后 ...

  7. Java 之常用API(一)

    常用API  1 API概述  2 Scanner类与String类  3 StringBuilder类 NO.one API概述 1.1 API概述 API(Application Programm ...

  8. JAVA中获取文件的大小和文件的扩展名

    一.获取文件扩展名(该段代码来自博客园网站装男人的博客https://www.cnblogs.com/nanrenzhuang/archive/2013/05/19/6315546.html) pub ...

  9. Android解析WindowManager(二)Window的属性

    前言 在上一篇文章我们学习了WindowManager体系,了解了Window和WindowManager之间的关系,这一篇我们接着来学习Window的属性. 1.概述 上一篇文章中我们讲过了Wind ...

  10. jquery 之节点操作

    一.添加节点 [添加内部子节点方法]:内部节点就是儿子节点 append()    在被选元素内部的结尾插入内容 appendTo()  将指定内容插入到被选标签内部的结尾 prepend()   在 ...