我目前正在使用带有蓝图的 Flask 应用程序工厂模式。我遇到的问题是如何访问应用程序工厂之外的 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)
必须有一种更好的方法,然后在应用程序中传递全局字典,正确吗?