繁体   English   中英

蓝图的蓝图(烧瓶)

[英]blueprint of blueprints (Flask)

我有一系列正在使用的蓝图,我希望能够将它们进一步捆绑到一个包中,我可以尽可能无缝地与任意数量的其他应用程序一起使用。 为应用程序提供整个引擎的一组蓝图。 我创建了自己的解决方案,但它是手动的,需要付出太多努力才能有效。 它看起来不像是一个扩展,它不仅仅是一个蓝图(几个提供了一个共同的功能)。

这样做了吗? 如何?

(将多个程序捆绑在一起的应用程序调度方法可能不是我正在寻找的)

我希望 Blueprint 对象有一个 register_blueprint 函数,就像 Flask 对象一样。 它会自动在当前蓝图的 url 下放置和注册蓝图。

最简单的方法是创建一个函数,该函数接受一个Flask应用程序的实例,并一次性在其上注册所有蓝图。 像这样的东西:

# sub_site/__init__.py
from .sub_page1 import bp as sb1bp
from .sub_page2 import bp as sb2bp
# ... etc. ...

def register_sub_site(app, url_prefix="/sub-site"):
    app.register_blueprint(sb1bp, url_prefix=url_prefix)
    app.register_blueprint(sb2bp, url_prefix=url_prefix)
    # ... etc. ...


# sub_site/sub_page1.py
from flask import Blueprint

bp = Blueprint("sub_page1", __name__)

@bp.route("/")
def sub_page1_index():
    pass

或者,您可以使用类似HipPocketautoload功能(完全披露:我写了HipPocket )来简化导入处理:

# sub_site/__init__.py
from hip_pocket.tasks import autoload

def register_sub_site(app,
                          url_prefix="/sub-site",
                          base_import_name="sub_site"):
    autoload(app, base_import_name, blueprint_name="bp")

但是,就目前而言,您不能使用与示例 #1 相同的结构(HipPocket 假设您为每个蓝图使用包)。 相反,您的布局将如下所示:

# sub_site/sub_page1/__init__.py
# This space intentionally left blank

# sub_site/sub_page1/routes.py
from flask import Blueprint

bp = Blueprint("sub_page1", __name__)

@bp.route("/")
def sub_page1_index():
    pass

看看这个:嵌套蓝图https://flask.palletsprojects.com/en/2.0.x/blueprints/#nesting-blueprints

parent = Blueprint('parent', __name__, url_prefix='/parent')
child = Blueprint('child', __name__, url_prefix='/child')
parent.register_blueprint(child)
app.register_blueprint(parent)

我有自己的解决方案如何加载配置中定义的蓝图,这样你就可以在配置中有类似CORE_APPS = ('core', 'admin', 'smth')的东西,当你构建应用程序时,你可以注册这些应用程序(当然CORE_APPS 中的那些字符串必须是您要在您的 python 路径中导入的文件的名称)。

所以我使用函数来创建应用程序:

app = create_app()

def create_app():
  app = Flask(__name__)

  # I have class for my configs so configuring from object
  app.config.from_object('configsClass')

  # does a lot of different stuff but the main thing could help you:
  from werkzeug.utils import import_string
  for app in app.config['CORE_APPS']
    real_app = import_string(app)
    app.register_blueprint(real_app)

之后,您的蓝图应该被注册。 当然,您可以在配置中使用不同的格式来支持自定义 url 前缀等等:)

当然,您也可以在主蓝图中执行类似操作,因此在创建应用程序时,您需要注册该主蓝图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM