我正在构建 Flask Web 应用程序,用户可以在其中启动和管理流程。这些进程正在进行一些繁重的计算(甚至可能需要几天)。当进程运行时,它将一些部分结果保存到文件中以供使用。
因此,当用户启动新进程时,我生成新线程并将线程句柄保存到flask.g全局变量中。
def add_thread(thread_handle):
ctx = app.app_context()
threads = flask.g.get("threads", [])
threads.append(thread_handle)
g.threads = threads
ctx.push()
稍后在需要时,用户可以终止长时间运行的进程。
def kill_thread(idx):
ctx = app.app_context()
threads = flask.g.get("threads", [])
threads.pop(idx).terminate()
g.threads = threads
ctx.push()
我必须使用 ctx.push() 来存储线程列表,因此在下一个请求时,列表可用。但这种方式在添加新线程时会引发有关应用程序上下文的异常。
Traceback (most recent call last):
File "/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site-packages/flask/app.py", line 1825, in wsgi_app
ctx.auto_pop(error)
File "/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site-packages/flask/ctx.py", line 374, in auto_pop
self.pop(exc)
File "/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site-packages/flask/ctx.py", line 366, in pop
app_ctx.pop(exc)
File "/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site-packages/flask/ctx.py", line 178, in pop
% (rv, self)
AssertionError: Popped wrong app context. (<flask.ctx.AppContext object at 0x10fb99c50> instead of <flask.ctx.AppContext object at 0x10fa60150>)
这开始让人感觉是一种错误的解决方案,并且在以后的开发中可能会出现死胡同。我正在考虑将句柄存储在文件/数据库中,但锁定对象无法被腌制。
是否有像我描述的那样管理实时 python 对象的设计模式?