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

查看:138

蓝图是用于生成Web应用程序的部分的模板。把它想象成一个模子:



你可以把蓝图应用到你的应用程序的几个地方。你每次申请蓝图,都会在你的应用程序中创建一个新的结构。

 #例子
from flask import蓝图

tree_mold =蓝图(mold,__name__)

@ tree_mold.route(/ leaves)
def leaves ):
return这棵树有叶子

@ tree_mold.route(/ roots)
def roots():
return

@ tree_mold.route(/ rings)
@ tree_mold.route(/ rings /< int:year>)
def rings(year = None ):
returnLooking the rings for {year}。format(year = year)



这是一个简单的树木工作模式 - 它说任何处理树木的应用程序都应该提供访问它的树叶,树根和环(每年)。它本身就是一个空心的壳 - 它无法路由,它不能作出反应,直到它给一个应用程序留下印象:

  from tree_workshop import tree_mold 
$ b $ 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 指定的位置上的应用程序的蓝图模具。

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

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.

解决方案

A blueprint is a template for generating a "section" of a web application. Think of it like 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 than 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")

Once it is created it may "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天全站免登陆