Python 在应用程序工厂外访问应用程序配置

Python 在应用程序工厂外访问应用程序配置,python,flask,Python,Flask,我目前正在使用带有蓝图的Flask应用程序工厂模式。我遇到的问题是如何在应用程序工厂之外访问app.config对象 我不需要Flask应用程序中的所有配置选项。我只需要6把钥匙。因此,我目前的做法是在调用create_应用程序(application factory)时,我基本上创建了一个global_config dictionary对象,并将global_config dictionary设置为具有我需要的6个键 然后,其他需要这些配置选项的模块只需导入全局配置字典 我在想,一定有更好的方

我目前正在使用带有蓝图的Flask应用程序工厂模式。我遇到的问题是如何在应用程序工厂之外访问app.config对象

我不需要Flask应用程序中的所有配置选项。我只需要6把钥匙。因此,我目前的做法是在调用create_应用程序(application factory)时,我基本上创建了一个global_config dictionary对象,并将global_config dictionary设置为具有我需要的6个键

然后,其他需要这些配置选项的模块只需导入全局配置字典

我在想,一定有更好的方法来做对吗

那么,关于代码

我当前的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
需要访问这些全局配置选项的模块示例:

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)

必须有一种更好的方法,然后在应用程序周围传递一个全局字典,对吗?

这里不需要使用全局名称,这首先就违背了使用应用程序工厂的目的

在视图中(例如在您的示例中)绑定到处理当前应用/请求上下文的应用

from flask import current_app

@bp.route('/')
def example():
    servers = current_app.config['CUPS_SERVERS']
    ...
如果您在设置蓝图时需要访问应用程序,则装饰程序会标记调用的函数的状态为蓝图正在注册的状态

@bp.record
def setup(state):
    servers = state.app.config['CUPS_SERVERS']
    ...

set_global_config
中,为什么不直接执行
global_config.update(app_config)
,因为您似乎想按原样复制所有键/值?甚至更简单:
global\u config=app\u config.copy()
。这不是一个答案,只是一个简单的评论。嗯,这是有道理的,我现在就做这个改变。谢谢您认为存储这些配置详细信息并传递它们有什么问题吗?