blu*_*ank 5 python web-services web-applications blueprint flask
我有一系列正在使用的蓝图,我希望能够将它们进一步捆绑到一个包中,以便可以与任何其他数量的其他应用程序无缝地使用。一整套为应用程序提供整个引擎的蓝图。我创建了自己的解决方案,但是它是手动的,需要花费大量的精力才能有效。它似乎不像是一个扩展,它不止一个蓝图(有几个提供共同的功能)。
完成了吗 怎么样?
(将几个程序捆绑在一起的应用程序分派方法可能不是我想要的)
看看这个:嵌套蓝图\xe2\x86\x92 https://flask.palletsprojects.com/en/2.0.x/blueprints/#nesting-blueprints
\nparent = Blueprint(\'parent\', __name__, url_prefix=\'/parent\')\nchild = Blueprint(\'child\', __name__, url_prefix=\'/child\')\nparent.register_blueprint(child)\napp.register_blueprint(parent)\nRun Code Online (Sandbox Code Playgroud)\n
最简单的方法是创建一个函数,该函数获取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
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用类似 的HipPocket函数autoload(完全公开:我写的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")
Run Code Online (Sandbox Code Playgroud)
然而,就目前情况而言,您无法使用与示例 #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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4603 次 |
| 最近记录: |