我正在构建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()
以后需要时,用户可以终止长时间运行的进程。在
^{pr2}$我不得不用ctx.推送()以存储线程列表,以便在下一个请求中,列表可用。但这种方式在添加新线程时会引发应用程序上下文异常。在
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>)
这开始让人觉得这是一种错误的解决方案,在以后的开发中可能会出现死胡同。我正在考虑将句柄存储在文件/数据库中,但是锁对象不能被pickle。在
有没有像我描述的那样管理实时python对象的设计模式?在
你最好使用
celery
(赛利项目网)对于这种任务。它在生产环境中大量使用,无需担心后期开发中的死角。它拥有管理后台任务所需的一切,以及更多。以下是如何integrate it with flask。在相关问题 更多 >
编程相关推荐