【发布时间】:2016-04-05 19:13:31
【问题描述】:
我目前正在使用带有蓝图的 Flask 应用程序工厂模式。我遇到的问题是如何在应用程序工厂之外访问 app.config 对象?
我不需要 Flask 应用程序中的所有配置选项。我只需要6把钥匙。所以我目前这样做的方式是在调用 create_app(application factory) 时,我基本上创建了一个 global_config 字典对象,我只是将 global_config 字典设置为具有我需要的 6 个键。
然后,需要这些配置选项的其他模块,他们只需导入 global_config 字典。
我在想,一定有更好的方法来做到这一点,对吧?
所以,开始代码
我当前的 init.py 文件:
def set_global_config(app_config):
global_config['CUPS_SAFETY'] = app_config['CUPS_SAFETY']
global_config['CUPS_SERVERS'] = app_config['CUPS_SERVERS']
global_config['API_SAFE_MODE'] = app_config['API_SAFE_MODE']
global_config['XSS_SAFETY'] = app_config['XSS_SAFETY']
global_config['ALLOWED_HOSTS'] = app_config['ALLOWED_HOSTS']
global_config['SQLALCHEMY_DATABASE_URI'] = app_config['SQLALCHEMY_DATABASE_URI']
def create_app(config_file):
app = Flask(__name__, instance_relative_config=True)
try:
app.config.from_pyfile(config_file)
except IOError:
app.config.from_pyfile('default.py')
cel.conf.update(app.config)
set_global_config(app.config)
else:
cel.conf.update(app.config)
set_global_config(app.config)
CORS(app, resources=r'/*')
Compress(app)
# Initialize app with SQLAlchemy
db.init_app(app)
with app.app_context():
db.Model.metadata.reflect(db.engine)
db.create_all()
from authenication.auth import auth
from club.view import club
from tms.view import tms
from reports.view import reports
from conveyor.view import conveyor
# Register blueprints
app.register_blueprint(auth)
app.register_blueprint(club)
app.register_blueprint(tms)
app.register_blueprint(reports)
app.register_blueprint(conveyor)
return app
需要访问这些 global_config 选项的模块示例:
from package import global_config as config
club = Blueprint('club', __name__)
@club.route('/get_printers', methods=['GET', 'POST'])
def getListOfPrinters():
dict = {}
for eachPrinter in config['CUPS_SERVERS']:
dict[eachPrinter] = {
'code': eachPrinter,
'name': eachPrinter
}
outDict = {'printers': dict, 'success': True}
return jsonify(outDict)
必须有比在应用程序周围传递全局字典更好的方法吗?
【问题讨论】:
-
in
set_global_config为什么不直接做global_config.update(app_config)因为您似乎想按原样复制所有键/值?甚至更简单:global_config = app_config.copy()。这不是一个答案,只是一个简单的评论。 -
嗯,这确实有道理,我现在就做出改变。谢谢。您是否发现存储这些配置详细信息并传递它们有任何问题?