Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样创建蓝图并注册到 Flask 应用?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

创建 Blueprint("reports", __name__),在蓝图上注册视图。工厂用 app.register_blueprint(..., url_prefix="/reports") 将它挂到应用中。

讲清原理

蓝图自己的子路径与 URL 前缀组合。url_for 用带蓝图名的端点,如 reports.detail。前缀和端点名是两套不同的名字。

例子与易错点

示例生成详情 URL 并用测试客户端请求。这样可以同时检查路径是否正确、模板将生成哪个链接。

from flask import Blueprint, Flask, url_for

reports = Blueprint("reports", __name__)

@reports.get("/<int:report_id>")
def detail(report_id):
    return {"report_id": report_id}

app = Flask(__name__)
app.register_blueprint(reports, url_prefix="/reports")
with app.test_request_context():
    path = url_for("reports.detail", report_id=7)
assert path == "/reports/7"
assert app.test_client().get(path).json == {"report_id": 7}
print(path)

相关题:第 85 题、第 87 题、第 88 题、第 89 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。