当前位置:网站首页>Flask1.1.4 werkzeug1.0.1 source code analysis: Blueprint
Flask1.1.4 werkzeug1.0.1 source code analysis: Blueprint
2022-07-28 02:27:00 【An engineer$】
Blueprints are used in daily projects to group user side and management side api, Use different prefixes . Today, let's explore the principle behind the blueprint .
Let's first look at an example of using blueprints .
from flask import Flask, Blueprint
# Instantiation
app = Flask(__name__)
# Building blueprint objects
some_blueprint = Blueprint('some', __name__)
# Use the method of blueprint object to decorate view_function
@some_blueprint.route("/a")
def hello_world():
return "<p>Hello, World!</p>"
# Register blueprints with flask_app
app.register_blueprint(some_blueprint, url_prefix='/pre')
We have figured out the previous series Flask take url_rule and view_function Save them separately to url_map and view_functions Properties of the . Blueprints are just a new form of routing packet management , Ultimately, the information in the blueprint must be saved to the same place in the same way , Let's study the process .
Let's start with @some_blueprint.route(“/a”)
class Blueprint(_PackageBoundObject):
def route(self, rule, **options):
# and flask_app.route() Like a hair
def decorator(f):
# endpoint Default function name
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
# The parameter is one function !
# This function is closed Routing and function related information
self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))
def record(self, func):
# self.deferred_functions It's a []
# Here is simply to save this function to the blueprint object
self.deferred_functions.append(func)
By the visible on , The blueprint Simple will Information such as routes and functions are saved , It's just a special way to save , Save this anonymous function lambda s: s.add_url_rule(rule, endpoint, view_func, **options) , You will see later that you are registering blueprints to flask_app When , Will call this function .
Let's take a look app.register_blueprint(some_blueprint, url_prefix=‘/pre’)
class Flask(_PackageBoundObject):
@setupmethod
def register_blueprint(self, blueprint, **options):
first_registration = False
# call buleprint Methods
# The first parameter is zero flask_app
blueprint.register(self, options, first_registration)
class Blueprint(_PackageBoundObject):
def make_setup_state(self, app, options, first_registration=False):
# The first parameter Blueprint example
# The second parameter flask_app example
return BlueprintSetupState(self, app, options, first_registration)
def register(self, app, options, first_registration=False):
self._got_registered_once = True
# state It's a BlueprintSetupState example The following research
state = self.make_setup_state(app, options, first_registration)
# Before Blueprint.route() Saved function list In turn, calls
for deferred in self.deferred_functions:
# Remember deferred The function is lambda s: s.add_url_rule(rule, endpoint, view_func, **options)
# in other words deferred(state) Would call state.add_url_rule(rule, endpoint, view_func, **options)
deferred(state)
cli_resolved_group = options.get("cli_group", self.cli_group)
look down BlueprintSetupState class
class BlueprintSetupState(object):
def __init__(self, blueprint, app, options, first_registration):
self.app = app
self.blueprint = blueprint
self.options = options
# first Use flask_app.register_blueprint() When it came in url_prefix
# If not Reuse Blueprint Of url_prefix
url_prefix = self.options.get("url_prefix")
if url_prefix is None:
url_prefix = self.blueprint.url_prefix
self.url_prefix = url_prefix
# above deferred(state) This method is called
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
if self.url_prefix is not None:
if rule:
# both url_prefix And then there is url_rule Under the circumstances Splice both
rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))
else:
rule = self.url_prefix
# endpoint By default, the function name
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
defaults = self.url_defaults
# Eventually Go to the flask_app.add_url_rule
# Pay attention to endpoint by {bulprint.name}.{endpoint} Very reasonable. Full paths should be used to avoid duplication of elements within a group
self.app.add_url_rule(
rule,
"%s.%s" % (self.blueprint.name, endpoint),
view_func,
defaults=defaults,
**options
)
Sum up :
- Blueprint Contains a set of routing information , You can use a uniform prefix . There is an interesting design in Blueprint.deferred_functions Property is a Anonymous function object lambda s: s.add_url_rule(rule, endpoint, view_func, **options), Anonymous function closures contain information such as routing .
- flask.register_blueprint() It finally triggered Blueprint.deferred_functions Function call in sequence , But it is not directly transmitted flask_app, But use BlueprintSetupState This holder class Some information is recorded and preprocessed , Then pass it as a parameter . Final , call BlueprintSetupState.add_url_rule(), Its internal finally calls flask_app.add_url_rule()
边栏推荐
- MySQL's way to solve deadlock - lock analysis of common SQL statements
- Feign calls get and post records
- 软考 --- 数据库(2)关系模型
- Wechat campus bathroom reservation applet graduation design finished product (1) development outline
- "Risking your life to upload" proe/creo product structure design - seam and buckle
- Leetcode hot topic Hot 100 - > 1. Sum of two numbers
- MySQL是如何利用索引的(荣耀典藏版)
- MySQL锁系列之锁算法详解(荣耀典藏版)
- Understand the "next big trend" in the encryption industry - ventures Dao
- 【HCIP】BGP 特性
猜你喜欢

Read Plato & nbsp; Eplato of farm and the reasons for its high premium
![[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control](/img/7f/f0360210e8a9f7e45410d79635bfd9.png)
[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control

学会这招再也不怕手误让代码崩掉

借助Elephant&nbsp;Swap打造的ePLATO,背后的高溢价解析

【ROS进阶篇】第九讲 基于Rviz和Arbotix控制的机器人模型运动

Flex development web page instance web side

APP如何上架App Store?

Appium click operation sorting

Go learn 02 basic knowledge
![[database data recovery] data recovery case of insufficient disk space of SQL Server database](/img/0e/908db40e1e8b7dd62e12558c1c6dc4.png)
[database data recovery] data recovery case of insufficient disk space of SQL Server database
随机推荐
Flex layout - fixed positioning + flow layout - main axis alignment - side axis alignment - expansion ratio
智能合约安全——selfdestruct攻击
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
This operation may not be worth money, but it is worth learning | [batch cutting of pictures]
【Star项目】小帽飞机大战(六)
[website construction] update SSL certificate with acme.sh: change zerossl to letsencrypt
Flex布局—固定定位+流式布局—主轴对齐—侧轴对齐—伸缩比
Codeforces Round #807 (Div. 2) A-C题解
剑指offer专项突击版第12天
11 Django basics database operation
Promise从入门到精通 (第2章 Promise的理解和使用)
这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
OBS键盘插件自定义diy
pytorch优化器设置
Two ways for wechat applet to realize dynamic horizontal step bar
数字赋能 创新未来:海丝埃睿迪亮相第五届数字中国建设峰会
四种常见的 POST 提交数据方式
Flex development web page instance web side
OBS keyboard plug-in custom DIY
Talk to ye Yanxiu, an atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?