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

蓝图怎样组织路由、模板和静态文件?

查看完整题解

参考回答

直接回答

在 Blueprint 上注册路由,并用 template_folder、static_folder 配置资源。模板目录可以再放一层蓝图名,避免多个业务使用相同模板路径。

讲清原理

蓝图静态文件用自身端点构建 URL,例如 url_for("reports.static", filename="chart.js")。如果蓝图没有前缀并与应用静态路径冲突,这条蓝图静态路由不会覆盖应用规则。部署在不同前缀时,也不要手写完整地址。

例子与易错点

示例用报表页引用 reports/index.html,业务代码也能一眼看出模板归属。检查最终地址时,可用测试客户端检查模板正文和静态端点。

from pathlib import Path
from tempfile import TemporaryDirectory

from flask import Blueprint, Flask, render_template, url_for

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    (root / "templates/reports").mkdir(parents=True)
    (root / "static").mkdir()
    (root / "templates/reports/index.html").write_text("<p>Monthly reports</p>")
    (root / "static/report.css").write_text("body { color: black; }")
    reports = Blueprint("reports", __name__, root_path=root,
                        template_folder="templates", static_folder="static")

    @reports.get("/")
    def home():
        return render_template("reports/index.html")

    app = Flask(__name__)
    app.register_blueprint(reports, url_prefix="/reports")
    with app.test_request_context():
        resource = url_for("reports.static", filename="report.css")
    client = app.test_client()
    assert client.get("/reports/").text == "<p>Monthly reports</p>"
    assert client.get(resource).status_code == 200
    print(resource)

相关题:第 93 题、第 102 题、第 103 题。

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

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