python - 在主类之外访问烧瓶上下文
问题描述
我是 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:
但它似乎没有用。
我做错了什么?
解决方案
你的问题就在这里。
我需要在主类之外访问应用程序
而你正试图以错误的方式解决它。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.
推荐阅读
- javascript - 如何更新第一个 td 值 onclick 拖动时的方式
- android - 退出应用程序时如何删除我的应用程序缓存?
- android - 如何让后退按钮正确反转片段之间的过渡动画?
- python - python中高效的在线线性回归算法
- javascript - JavaScript:为什么控制台不被视为标准的内置对象?
- php - laravel eloquent ->whereHas - 编写你自己的存在(子查询)
- python-3.x - 启动实例时出现 Amazon EC2 错误 已达到最大 VPC 数
- bitbucket - 无法将 Git 存储库克隆到源树中,登录屏幕不断出现
- android - 如何从视频 URL 获取视频缩略图作为 GIF?
- azure - Azure CDN - 以某种方式截断“大文件”?