What are Flask Blueprints, exactly?

后端 未结 5 2005
感动是毒
感动是毒 2020-12-12 08:22

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 co

5条回答
  •  情歌与酒
    2020-12-12 09:12

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

    A medallion mold with a gold medallion freshly removed from it

    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/")
    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")
    

    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.

提交回复
热议问题