蓝图#
蓝图允许模块化代码,当路由开始跨多个模块时,应该使用它们。蓝图与应用程序一样,可以拥有模板和静态文件,因此一个名为 store
的蓝图的典型文件夹结构将是:
blueprints/
blueprints/store/__init__.py
blueprints/store/templates/
blueprints/store/templates/index.html
blueprints/store/static/
__init__.py
文件应包含类似以下内容的内容:
from quart import Blueprint
blueprint = Blueprint('store', __name__)
@blueprint.route('/')
async def index():
return await render_template('index.html')
然后,端点将被标识为 store.index
,例如当使用 url_for('store.index')
时。
嵌套蓝图#
可以在另一个蓝图上注册蓝图。
parent = Blueprint("parent", __name__, url_prefix="/parent")
child = Blueprint("child", __name__, url_prefix="/child")
parent.register_blueprint(child)
app.register_blueprint(parent)
子蓝图将获得父蓝图名称作为其名称的前缀,并且子 URL 将以父蓝图的 URL 前缀作为前缀。
url_for('parent.child.create')
/parent/child/create
在父级上注册的特定于蓝图的请求前函数等将针对子级触发。如果子级没有能够处理给定异常的错误处理程序,则将尝试父级的错误处理程序。