我正在尝试访问
python-socketio
的事件处理程序 on_tick()
中的 Flask 应用程序上下文,并且出现错误 -
(...)
File "H:\Python\autotrader2\venv\lib\site-packages\werkzeug\local.py", line 316, in __get__
obj = instance._get_current_object() # type: ignore[misc]
File "H:\Python\autotrader2\venv\lib\site-packages\werkzeug\local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
尝试提取一个较大程序的自给自足的微型版本 -
import socketio
from flask import current_app
class MySocketIOClient:
def __init__(self):
self.sio = socketio.Client()
self.sio.connect("https://feeds.sio.server",
headers={"User-Agent": "python-socketio[client]/socket"},
auth={"user": "user_id", "token": "session_token"},
transports="websocket")
def execute(self):
# with current_app.app_context(): # Does not work
with current_app.test_request_context('/'): # Does not work
self.sio.on('update', self.on_tick)
# self.sio.wait() # Does not work either
def on_tick(self, tick):
print(tick)
# Error: working outside application context
print("APP_TIMEZONE={}".format(current_app.config.get('APP_TIMEZONE')))
if __name__ == '__main__':
MySocketIOClient().execute()
如何在事件处理程序中访问 Flask 的应用程序上下文(或请求上下文)?
current_app
仅在已经安装了应用程序上下文时才有效,因此它对您的情况没有用。
为此,您需要导入您的应用程序实例:
from x import app
class MySocketIOClient:
# ...
def on_tick(self, tick):
print("APP_TIMEZONE={}".format(app.config.get('APP_TIMEZONE')))
这里我使用
x
作为包含 Flask 应用程序实例的模块的占位符。