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‘)
时间: 2024-08-06 07:59:10

How Flask Routing Works的相关文章

webpack 单页面应用实战

这篇文章将介绍如何利用 webpack 进行单页面应用的开发,算是我在实际开发中的一些心得和体会,在这里给大家做一个分享.webpack 的介绍这里就不多说了,可以直接去官网查看. 关于这个单页面应用大家可以直接去我的github上查看https://github.com/huangshuwei/webpackForSPA,我将结合这个项目去介绍.如果大家觉得这篇文章有不妥的地方,还请指出. 这篇文章的目的是解决我们在开发中会遇到的问题,不是一篇基础教程,还请谅解. 项目目录 我将根据这个目录结

【转】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 2vote 3vote 4vote 5 A deeper look into the two pillars of ASP.NET MVC – Routers and Controllers. Introduction ASP.NET MVC provides a new way of creati

The main concepts

The MVC application model A Play application follows the MVC architectural pattern applied to the web architecture. This pattern splits the application into separate layers: the Presentation layer and the Model layer. The Presentation layer is furthe

Flask error: werkzeug.routing.BuildError

@main.route('/sendfile', methods=['GET', 'POST']) def sendfile():     if request.method == 'POST':         f = request.files['file']         basepath = path.abspath(path.dirname(__file__))         upload_path = path.join(basepath, 'static/uploads')  

flask报错:werkzeug.routing.BuildError: Could not build url for endpoint &#39;index&#39;. Did you mean &#39;single&#39; instead?

错误代码 参考:https://blog.csdn.net/qq_27468251/article/details/81359701 改为 flask报错:werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'single' instead? 原文地址:https://www.cnblogs.com/MC-Curry/p/9748358.html

Flask之 路由(routing)

# -*- coding:utf-8 -*- from flask import Flask #创建一个flask应用对象 app = Flask(__name__) app.debug = True #使用 route()装饰器告诉flask哪个url触发哪个函数 @app.route('/') def hello_world(): return 'Index page' #route()装饰器绑定了一个函数hello()到一个URL "/hello" @app.route('/he

Flask中endpoint的理解

在flask框架中,我们经常会遇到endpoint这个东西,最开始也没法理解这个到底是做什么的.最近正好在研究Flask的源码,也就顺带了解了一下这个endpoint 首先,我们看一个例子: @app.route('/user/<name>') def user(name): return 'Hello, %s' % name 这个是我们在用flask框架写网站中最常用的. 通过看源码,我们可以发现: 函数等效于 def user(name) return 'Hello, %s' % name

Flask源码复习之路由

构建路由规则 一个 web 应用不同的路径会有不同的处理函数,路由就是根据请求的 URL 找到对应处理函数的过程. 在执行查找之前,需要有一个规则列表,它存储了 url 和处理函数的对应关系.最容易想到的解决方案就是定义一个字典,key 是 url,value 是对应的处理函数.如果 url 都是静态的(url 路径都是实现确定的,没有变量和正则匹配),那么路由的过程就是从字典中通过 url 这个 key ,找到并返回对应的 value:如果没有找到,就报 404 错误.而对于动态路由,还需要更

Flask学习笔记——配置管理

1.硬编码: app = Flask(__name__) # app.config 是flask.config.Config类的实例,继承自内置数据结构dict app.config['DEBUG'] = True 2.参考--flask.config.Config类: class Config(dict): """Works exactly like a dict but provides ways to fill it from files or special dict