使用Application Factory时获取配置值

时间:2016-03-09 15:12:06

标签: python flask

我想在运行视图之前检查一些配置,所以我为它编写了一个装饰器。但是,我无法获取配置,因为我正在使用应用程序工厂模式,因此在定义装饰器时尚未设置应用程序。我与处理应用程序上下文有关。

如果我还没有应用程序,如何访问配置?

from flask import Flask
from views import blueprint

def create_app():
    app = Flask(__name__)
    app.config['DECORATOR_KEY'] = 'decorator-key-here'
    app.register_blueprint(blueprint)
    return app

app = create_app()

if __name__ == '__main__':
    app.run()

decorators.py

import functools
from flask import current_app

DECORATOR_KEY = current_app.config.get('DECORATOR_KEY')

def key_length():
    return len(DECORATOR_KEY)

def config_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        print "Key Length: {}".format(key_length())
        return f(*args, **kwargs)
    return wrapper

views.py

from flask import Blueprint

blueprint = Blueprint('main', __name__)

@blueprint.route('/')
@config_decorator
def main():
    return "This is the only route."
File "app.py", line 3, in <module>
    from views import blueprint
  File "/Users/pat/Code/Playground/FactoryProblem/views.py", line 3, in <module>
    from decorators import config_decorator
  File "/Users/pat/Code/Playground/FactoryProblem/decorators.py", line 6, in <module>
    DECORATOR_KEY = current_app.config.get('DECORATOR_KEY')
  File "/Users/pat/.virtualenvs/factory/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/pat/.virtualenvs/factory/lib/python2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object
    return self.__local()
  File "/Users/pat/.virtualenvs/factory/lib/python2.7/site-packages/flask/globals.py", line 34, in _find_app
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

1 个答案:

答案 0 :(得分:1)

您无法在应用上下文之外使用current_app,但您在模块的顶层使用DECORATOR_KEY = current_app.config.get('DECORATOR_KEY')。将它移到装饰器包装器内部。

def key_length():
    DECORATOR_KEY = current_app.config['DECORATOR_KEY']
    return len(DECORATOR_KEY)

def config_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        print "Key Length: {}".format(key_length())
        return f(*args, **kwargs)
    return wrapper