烧瓶如何从另一个文件获取配置元素(例如:helper.py)

时间:2018-12-10 06:51:06

标签: python flask

美好的一天。 我有一个问题。如何从另一个.py文件访问配置项

例如。

app / __ init __。py

def create_app(config=None):
    app = Flask(__name__, instance_relative_config=True)   
    app._static_folder = './static'
    app.config.from_pyfile('flask.cfg')
    app.app_context().push()
    return app

wsgi.py

from app import create_app
from werkzeug.debug import DebuggedApplication


if __name__ == "__main__":
    app = create_app()
    application = DebuggedApplication(app, evalex=True)    
    app.logger.info("Debug status is: " + str(app.config['DEBUG']))
    app.run(use_reloader=True, debug=True)

app / core / helper.py

from flask import current_app as app

def get_dir():
    return app.config["PATH_CACHE_DIR"]
  

尝试调用方法app / core / cached.py

from flask_caching import Cache
from flask import current_app as app
from app.core.helper import get_dir

print get_dir()

所以,我收到以下错误消息

  Traceback (most recent call last):
  File "/home/stanislav/Python/mbgp/wsgi.py", line 1, in <module>
    from app import create_app
  File "/home/stanislav/Python/mbgp/app/__init__.py", line 4, in <module>
    from app.core.cached import cache
  File "/home/stanislav/Python/mbgp/app/core/cached.py", line 5, in <module>
    print get_dir()
  File "/home/stanislav/Python/mbgp/app/core/helper.py", line 14, in get_dir
    return app.config["PATH_CACHE_DIR"]
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current applicat`enter code here`ion object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

请告诉我如何解决此问题,非常感谢。

0 个答案:

没有答案