python – 在应用程序工厂外访问Flask配置
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 在应用程序工厂外访问Flask配置,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2470字,纯文字阅读大概需要4分钟。
内容图文
![python – 在应用程序工厂外访问Flask配置](/upload/InfoBanner/zyjiaocheng/710/be08e704bfc14723b6b302c96e072e3b.jpg)
我目前正在使用带有蓝图的Flask Application Factory模式.我遇到的问题是如何访问应用程序工厂外的app.config对象?
我不需要Flask应用程序中的所有配置选项.我只需要6把钥匙.所以我这样做的当前方式是在调用create_app(应用程序工厂)时,我基本上创建了一个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)
必须有一个更好的方法,然后围绕应用程序正确传递全局字典?
解决方法:
这里没有必要使用全局名称,这首先违背了使用app工厂的目的.
在视图中,例如在您的示例中,current_app绑定到处理当前应用程序/请求上下文的应用程序.
from flask import current_app
@bp.route('/')
def example():
servers = current_app.config['CUPS_SERVERS']
...
如果您在设置蓝图时需要访问应用程序,则record装饰器会标记使用注册蓝图的状态调用的函数.
@bp.record
def setup(state):
servers = state.app.config['CUPS_SERVERS']
...
内容总结
以上是互联网集市为您收集整理的python – 在应用程序工厂外访问Flask配置全部内容,希望文章能够帮你解决python – 在应用程序工厂外访问Flask配置所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。