什么是Flask设计图?

2024-06-01 08:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了关于蓝图的the official Flask documentation,甚至还有关于使用蓝图的onetwo博客文章。

我甚至在我的web应用程序中使用过它们,但我并不完全了解它们是什么,也不知道它们是如何融入我的应用程序的。它与我的应用程序实例有何相似之处,但并不完全相同?文件是全面的,但我寻求一个外行解释或启发性的类比,以激发它为我。当一位同事让我向他们解释一个瓶子的蓝图时,我感到非常困惑。


Tags: 文件the实例web应用程序flask瓶子documentation
2条回答

蓝图是生成web应用程序“部分”的模板。你可以把它想象成一个模子:

A medallion mold with a gold medallion freshly removed from it

您可以将蓝图应用到多个地方的应用程序中。每次应用时,蓝图将在应用程序的灰泥中创建其结构的新版本。

# 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)

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

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指定的位置“印象深刻”应用程序上蓝图的模型。

正如acomment by @Devasish中指出的,本文提供了一个很好的答案:

http://exploreflask.com/en/latest/blueprints.html

引用格罗姆的文章:

An example of this would be Facebook. If Facebook used Flask, it might have blueprints for the static pages (i.e. signed-out home, register, about, etc.), the dashboard (i.e. the news feed), profiles (/robert/about and /robert/photos), settings (/settings/security and /settings/privacy) and many more. These components all share a general layout and styles, but each has its own layout as well

这是一个很好的解释,尤其是“如果Facebook使用了烧瓶”这一部分。它给了我们一个具体的场景来可视化蓝图的实际工作方式。

相关问题 更多 >