究竟什么是 Flask 蓝图? [英] What are Flask Blueprints, exactly?

查看:39
本文介绍了究竟什么是 Flask 蓝图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经阅读了关于蓝图的Flask 官方文档,甚至一个两篇关于使用它们的博文.

I have read the official Flask documentation on Blueprints and even one or two blog posts on using them.

我什至在我的网络应用程序中使用过它们,但我不完全理解它们是什么或它们如何作为一个整体融入我的应用程序.它与我的应用程序实例有何相似但又不完全相同?文档很全面,但我寻求一个外行的解释或一个有启发性的类比来为我激发它.当一位同事让我向他们解释我选择在这里询问的 Flask 蓝图时,我感到非常困惑.

I've even used them in my web app, but I don't completely understand what they are or how they fit into my app as a whole. How is it similar to an instance of my app but not quite? The documentation is comprehensive but I seek a layman explanation or an enlightening analogy to spark it for me. I was sufficiently perplexed when a colleague asked me to explain a Flask blueprint to them that I elected to ask here.

推荐答案

蓝图是用于生成 Web 应用程序部分"的模板.你可以把它想象成一个模具:

A blueprint is a template for generating a "section" of a web application. You can think of it as a mold:

您可以将蓝图应用到您的应用程序的多个位置.每次您应用它时,蓝图都会在您的应用程序中创建一个新版本的结构.

You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.

# An example
from flask import Blueprint

tree_mold = Blueprint("mold", __name__)

@tree_mold.route("/leaves")
def leaves():
    return "This tree has leaves"

@tree_mold.route("/roots")
def roots():
    return "And roots as well"

@tree_mold.route("/rings")
@tree_mold.route("/rings/<int:year>")
def rings(year=None):
    return "Looking at the rings for {year}".format(year=year)

这是一个用于处理树木的简单模型 - 它说任何处理树木的应用程序都应该提供对它的叶子、根和年轮的访问(按年份).就其本身而言,它是一个空壳——它不能路由,不能响应,直到它被应用程序打动:

This is a simple mold for working with trees - it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell - it cannot route, it cannot respond, until it is impressed upon an application:

from tree_workshop import tree_mold

app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")

一旦创建,它可能会通过使用 register_blueprint 函数在应用程序上留下印象" - 这会在应用程序上由 url_prefix 指定的位置留下"蓝图的模具.

Once it is created it may be "impressed" on the application by using the register_blueprint function - this "impresses" the mold of the blueprint on the application at the locations specified by url_prefix.

这篇关于究竟什么是 Flask 蓝图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆