Python 3.x 弹出Flask应用程序上下文时出错
我正在尝试使用线程创建一个异步API(在我的例子中,芹菜是一种过度使用)。为了达到同样的目的,我以下面的方式对Thread类进行了子类化。由于将在线程内运行的代码需要应用程序和请求上下文,因此我将这两个上下文都推送到了堆栈中Python 3.x 弹出Flask应用程序上下文时出错,python-3.x,multithreading,flask,asynchronous,Python 3.x,Multithreading,Flask,Asynchronous,我正在尝试使用线程创建一个异步API(在我的例子中,芹菜是一种过度使用)。为了达到同样的目的,我以下面的方式对Thread类进行了子类化。由于将在线程内运行的代码需要应用程序和请求上下文,因此我将这两个上下文都推送到了堆栈中 from threading import Thread from flask import _app_ctx_stack, _request_ctx_stack class AppContextThread(Thread): def __init__(sel
from threading import Thread
from flask import _app_ctx_stack, _request_ctx_stack
class AppContextThread(Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# App context and request context are popped from the stack once request is completed but we require them for
# accessing application data. Hence, storing them and then again pushing into the stack.
self.app_context = _app_ctx_stack.top
self.request_context = _request_ctx_stack.top
def run(self):
self.app_context.push()
self.request_context.push()
super().run()
print(f"App context top: {_app_ctx_stack.top}")
print(f"Req context top: {_request_ctx_stack.top}")
print(f"After app_context: {self.app_context}")
print(f"After request_context: {self.request_context}")
self.request_context.pop()
print(f"After request_context pop: {self.request_context}")
print(f"After request_context pop -> app_context: {self.app_context}")
self.app_context.pop()
print(f"After app_context pop: {self.app_context}")
现在,当我尝试将应用程序上下文从堆栈中弹出时,即使应用程序上下文存在于堆栈中,我也会遇到以下错误(打印了相同的日志)
应用程序上下文顶部:
请求上下文顶部:
在应用程序上下文之后:
请求后的上下文:
请求后\u上下文弹出:
请求后\u上下文弹出->应用程序\u上下文:
回溯(最近一次呼叫最后一次):
文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py”,第916行,在bootstrap\u内部
self.run()
文件“/Users/app/utils/app\u context\u thread.py”,第27行,运行中
self.app_context.pop()
文件“/Users/venv/lib/python3.6/site packages/flask/ctx.py”,第235行,pop格式
%(rv,自我)
AssertionError:弹出了错误的应用程序上下文。(无代替)
有人能指出我做错了什么吗
App context top: <flask.ctx.AppContext object at 0x7f7f512100f0>
Req context top: <RequestContext 'http://0.0.0.0:8000/rest/v1/api' [PUT] of app.app>
After app_context: <flask.ctx.AppContext object at 0x7f7f512100f0>
After request_context: <RequestContext 'http://0.0.0.0:8000/rest/v1/api' [PUT] of app.app>
After request_context pop: <RequestContext 'http://0.0.0.0:8000/rest/v1/api' [PUT] of app.app>
After request_context pop -> app_context: <flask.ctx.AppContext object at 0x7f7f512100f0>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Users/app/utils/app_context_thread.py", line 27, in run
self.app_context.pop()
File "/Users/venv/lib/python3.6/site-packages/flask/ctx.py", line 235, in pop
% (rv, self)
AssertionError: Popped wrong app context. (None instead of <flask.ctx.AppContext object at 0x7f7f512100f0>)