简体   繁体   English

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

[英]Access Flask config outside of application factory

I'm currently using the Flask Application Factory pattern with Blueprints.我目前正在使用带有蓝图的 Flask 应用程序工厂模式。 The issue that I'm having is how do I access the app.config object outside of the application factory?我遇到的问题是如何访问应用程序工厂之外的 app.config 对象?

I don't need all the configuration options from the Flask app.我不需要 Flask 应用程序中的所有配置选项。 I just need 6 keys.我只需要6把钥匙。 So the current way I do this is when the create_app(application factory) is called, I basically create a global_config dictionary object and I just set the global_config dictionary to have the 6 keys that I need.所以我目前的做法是在调用 create_app(application factory) 时,我基本上创建了一个 global_config 字典对象,我只是将 global_config 字典设置为具有我需要的 6 个键。

Then, the other modules that need those configuration options, they just import global_config dictionary.然后,其他需要这些配置选项的模块,他们只需导入 global_config 字典。

I'm thinking, there has to be a better way to do this right?我在想,必须有更好的方法来做到这一点,对吗?

So, on to the code所以,进入代码

My current init .py file:我当前的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

An example of a module that needs access to those global_config options:需要访问这些 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)

There has to be a better way then passing a global dictionary around the application correct?必须有更好的方法然后在应用程序周围传递全局字典正确吗?

There is no need to use global names here, that defeats the purpose of using an app factory in the first place.这里不需要使用全局名称,这首先违背了使用应用程序工厂的目的。

Within views, such as in your example, current_app is bound to the app handling the current app/request context.在视图中,例如在您的示例中, current_app绑定到处理当前应用程序/请求上下文的应用程序。

from flask import current_app

@bp.route('/')
def example():
    servers = current_app.config['CUPS_SERVERS']
    ...

If you need access to the app while setting up a blueprint, the record decorator marks functions that are called with the state the blueprint is being registered with.如果您在设置蓝图时需要访问应用程序, record装饰器会标记使用蓝图注册状态调用的函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM