首页 > 解决方案 > 在主类之外访问烧瓶上下文

问题描述

我是 python 新手,因此我相信解决方案可能很快。我花了几个小时,但无法让它工作。

我需要在主类之外访问应用程序。包结构如下:

app/
   app.py
   another_class.py

在 app.py 中:

app = Flask(__name__)

在 another_class.py 中:

from flask import current_app as app

app.config['test_key']

当然我收到错误

RuntimeError: Working outside of application context.

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

我试过在块中运行它

with app.app_context:

但它似乎没有用。

我做错了什么?

标签: pythonflaskruntime-error

解决方案


你的问题就在这里。

我需要在主类之外访问应用程序

而你正试图以错误的方式解决它。current_app对于使用最初在外部使用的功能很有用。通常,一个用例是模拟路线,但离线。

您想要做的是拥有一个可以“管理”您的应用程序的文件,manage.py例如。然后,另一个文件app.py将包含您的应用程序的配置。

在您的manage.py文件中,您将import app运行它。如果您随后需要访问您的app对象,则可以import app从另一个文件中访问。基本上,app您在其中实例化的对象app.py就像一个指针,导入应用程序的其他文件也将受到您在另一个文件中对此对象所做的更改的影响app

你的树应该是这样的。

your_api/
    app.py # Instantiate the app object.
    manage.py # Import the app.py package to run it.
    another_file.py # If this file imports app.py and modifies the app object
                    # inside, the changes will also affect the object imported by manage.py.

推荐阅读