bigywater.tech
Flask · 26

Blueprint 路由注册

蓝图到底是什么?定义路由的时候路由在哪里?注册的时候发生了什么?钩子和错误处理器的范围有多大?这篇从 deferred_functions 开始逐项打印。

1
定义一个路由后蓝图上记录的延迟函数个数
parent.child.x
嵌套蓝图里路由的 endpoint
AssertionError
蓝图注册后再加路由时的报错

蓝图只是记录

实测 · 本机执行输出
  蓝图对象上记录的延迟函数 deferred_functions 个数: 1 | 类型: ['function']
  注册前 app.url_map 的规则: [] | app.blueprints = {}
  注册后 app.url_map 的规则: [('/ping', 'api.ping')] | app.blueprints = {'api': 'Blueprint'}

上一篇:路由冲突如何解决;下一篇:Blueprint 的 URL 前缀。

注册之后不能再加路由

实测 · 本机执行输出
  AssertionError: The setup method 'route' can no longer be called on the blueprint 'api'. It has already been registered at least once, any changes will not be applied consistently.

endpoint 与 request.blueprint

实测 · 本机执行输出
  请求 /shop/info 时: {'blueprint': 'shop', 'blueprints': ['shop'], 'endpoint': 'shop.info', 'rel': '/shop/info', 'abs': '/shop/info'}

嵌套蓝图

实测 · 本机执行输出
  规则: [('/p/c/x', 'parent.child.x')] | GET /p/c/x → child x
  请求里 request.blueprints = ['parent.child', 'parent'] | request.blueprint = parent.child

钩子与处理器的作用范围

实测 · 本机执行输出
  /b3/t   → 回调 ['b3.before_request'] | 模板里 who = who=b3
  /plain  → 回调 [] | 模板里 who=(无)
  蓝图的 errorhandler(404):GET /b3/nope → <!doctype html>
<html lang=en>
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
 (路由没匹配,不属于任何蓝图,用的是应用的默认 404)

拆分应用

实测 · 本机执行输出
    [('/shop/', 'shop.home'), ('/shop/<int:i>', 'shop.item')]
    shop home | item 3
    蓝图对象的 root_path: <项目>/shop

分步演示

Blueprint
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动
    • 没有验证:蓝图的 cli_group 与 flask 命令、url_defaults 与 url_value_preprocessor、蓝图 register 时的 options(如 subdomain)、更深层(三层以上)嵌套的钩子顺序
    京ICP备2026067502号-1京公网安备11010502063487号