在应用程序工厂外访问Flask配置 [英] Access Flask config outside of application factory

查看:77
本文介绍了在应用程序工厂外访问Flask配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将Flask Application Factory模式与蓝图一起使用.我遇到的问题是如何在应用程序工厂之外访问app.config对象?

I'm currently using the Flask Application Factory pattern with Blueprints. The issue that I'm having is how do I access the app.config object outside of the application factory?

我不需要Flask应用程序中的所有配置选项.我只需要6个键.因此,当前的操作方式是在调用create_app(应用程序工厂)时,我基本上创建了一个global_config字典对象,然后将global_config字典设置为具有我需要的6个键.

I don't need all the configuration options from the Flask app. I just need 6 keys. 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.

然后,需要这些配置选项的其他模块,它们仅导入global_config字典.

Then, the other modules that need those configuration options, they just import global_config dictionary.

我在想,必须有一种更好的方法来做到这一点吗?

I'm thinking, there has to be a better way to do this right?

因此,进入代码

我当前的 init .py文件:

My current init.py file:

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选项的模块的示例:

An example of a module that needs access to those global_config options:

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.

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

Within views, such as in your example, current_app is bound to the app handling the current app/request context.

from flask import current_app

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

如果您在设置蓝图时需要访问应用程序,请 record 装饰器标记以注册蓝图的状态调用的函数.

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.

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

这篇关于在应用程序工厂外访问Flask配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆