Python 如何在Django中从类似配置的应用程序注册烧瓶蓝图?
如何在Django中从类似配置的应用程序注册烧瓶蓝图 我想在配置文件中定义蓝图,它将自动注册Python 如何在Django中从类似配置的应用程序注册烧瓶蓝图?,python,django-apps,flask,Python,Django Apps,Flask,如何在Django中从类似配置的应用程序注册烧瓶蓝图 我想在配置文件中定义蓝图,它将自动注册 #config.py BLUEPRINTS = ( 'news', 'files', ) Flask不是Django,它没有这样的特性。 如果您确实需要,您可以尝试自己实施此行为: 假设您的中心烧瓶应用程序文件包含: import flask app = flask.Flask(__name__) 将BLUEPRINTS变量放入flask的配置(从_pyfile(…)向app.config.注册的配
#config.py
BLUEPRINTS = (
'news',
'files',
)
Flask不是Django,它没有这样的特性。 如果您确实需要,您可以尝试自己实施此行为: 假设您的中心烧瓶应用程序文件包含:
import flask
app = flask.Flask(__name__)
实际上,我在一个暂定名为。它与@HighCat给出的答案基本相同,只是它使用Python的打包系统,而不是
config.py
文件(尽管它可以扩展为从配置文件自动加载,这是最受欢迎的)
因此,在臀部口袋中,您可以这样做(请参阅了解其工作原理):
autoload
遍历一个包(默认名为“apps”,不过您可以通过传入关键字argapps\u package
来更改它),查找要在应用程序上注册的flask.Blueprint
对象(默认情况下,它在找到的每个子包中的名为routes
的模块中查找名为routes
的符号,但这些默认值也可以更改。)文件夹布局可能如下所示:
+ you_app
. . . . __init__.py
. . . . app.py
. . . . + apps
. . . . __init__.py
. . . . routes.py # contains the declaration `routes = Blueprint(...)`
. . . . + news
. . . . __init__.py
. . . . routes.py # Ditto
. . . . some_module.py
. . . . + files
. . . . __init__.py
. . . . routes.py # Ditto
. . . . # etc.
或者,如果您想使用基于配置的加载程序,可以执行以下操作:
from flask import Flask
from werkzeug.utils import import_string
app = Flask(__name__)
app.config.from_object("your_app.config")
for tool_path in app.config["BLUEPRINTS"]:
tool = import_string(tool_path)
app.register_blueprint(tool)
我知道Flask不是Django的克隆,我需要自己实现它。Basic我知道我需要迭代app.config['BLUEPRINTS',并使用
\uuuuuuu import\uuuu
。但是如何在没有eval()
的情况下注册由\uuuuuu import\uuuu导入的蓝图?尝试getattr()Smth类似于app.register\u Blueprint(getattr(\uu import>)__(模块名称),'thethethethethethethethethethethethethethethethethethetheheheBlueprint')。如果您的蓝图是包,请将“thethethethethethethethetheBlueprint”放在每个/theuuuuuuu init\uuuuuuuuuuuu.py中
from flask import Flask
from werkzeug.utils import import_string
app = Flask(__name__)
app.config.from_object("your_app.config")
for tool_path in app.config["BLUEPRINTS"]:
tool = import_string(tool_path)
app.register_blueprint(tool)