烧瓶:应用程序工厂是否需要蓝图? [英] Flask: are blueprints necessary for app factories?
问题描述
我想拥有几个应用程序工厂(当前:一个用于开发,另一个用于测试).我想知道实现它们的正确方法是什么.
I want to have several app factories(currently: one for development, and another one for testing). I am wondering what is the proper way to implement them.
当前,我使用应用程序对象注册视图(通过@app.route()
装饰器).我是否需要开始使用蓝图(而非应用程序)注册视图?有没有办法在没有blueprients的情况下拥有适当的应用程序工厂?
Currently I use app object to register views(via @app.route()
decorator). Do I need to start using blueprints(instead of app) to register views? Is there any way to have proper app factories without blueprients?
推荐答案
从技术上讲,您不需要蓝图,只需在create_app
函数上注册每条路线即可.一般来说,这不是一个好主意,这就是为什么存在蓝图的原因.
technically, you don't need blueprints, you can just register each route on your create_app
function. Generally speaking that's not a great idea, and it's kind of why blueprints exist.
没有蓝图的示例
def create_app():
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
return app
您可以拥有一个应用程序工厂来进行测试和其他配置(如果您以此方式配置).如果要根据测试是否加载其他蓝图,可以执行以下操作.
You can have a single app factory for both testing and whatever else if you configure it that way. If you want to load different blueprints based on if it is in testing, you can do something like this.
from project.config import configurations as c
def create_app(config=None):
" make the app "
app = Flask(__name__)
app.config.from_object(c.get(config, None) or c['default'])
configure_blueprints(app)
return app
def configure_blueprints(app):
" register the blueprints on your app "
if app.testing:
from project.test_bp import bp
app.register_blueprint(bp)
else:
from project.not_test_bp import bp
app.register_blueprint(bp)
然后project/config.py
可能像这样:
class DefaultConfig(object):
PROJECT_NAME = 'my project'
class TestingConfig(DefaultConfig):
TESTING = True
class DevConfig(DefaultConfig):
DEBUG = True
configurations = {
'testing': TestingConfig,
'dev': DevConfig,
'default': DefaultConfig
}
为每个蓝图创建一个文件夹,其中文件夹中的__init__.py
实例化该蓝图.假设有一个名为routes
Make a folder for each blueprint where the __init__.py
in the folder instantiates the blueprint. Let's say for a blueprint called routes
from flask import Blueprint
bp = Blueprint('routes', __name__)
from project.routes import views
然后在project/routes/views.py
中,您可以放置视图.
then in project/routes/views.py
, you can put your views.
from project.routes import bp
@bp.route('/')
def index():
return render_template('routes/index.html')
这篇关于烧瓶:应用程序工厂是否需要蓝图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!