Python 在flask应用程序中创建、管理和终止后台任务
我正在构建flask web应用程序,用户可以在其中启动和管理流程。这些过程正在进行一些繁重的计算(甚至可能需要几天)。在进程运行时,它会将部分结果保存到文件中以供使用 所以,当用户启动新进程时,我生成新线程并将线程句柄保存到flask.g全局变量中Python 在flask应用程序中创建、管理和终止后台任务,python,multithreading,flask,python-multithreading,Python,Multithreading,Flask,Python Multithreading,我正在构建flask web应用程序,用户可以在其中启动和管理流程。这些过程正在进行一些繁重的计算(甚至可能需要几天)。在进程运行时,它会将部分结果保存到文件中以供使用 所以,当用户启动新进程时,我生成新线程并将线程句柄保存到flask.g全局变量中 def add_thread(thread_handle): ctx = app.app_context() threads = flask.g.get("threads", []) threads.append(threa
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>)
回溯(最近一次呼叫最后一次):
文件“/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site packages/flask/app.py”,第1836行,在调用中__
返回self.wsgi_应用程序(环境,启动响应)
文件“/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site packages/flask/app.py”,第1825行,在wsgi_应用程序中
ctx.auto_pop(错误)
文件“/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site packages/flask/ctx.py”,第374行,自动弹出
self.pop(exc)
文件“/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site packages/flask/ctx.py”,第366行,pop格式
app_ctx.pop(exc)
文件“/Users/mirobeka/.virtualenvs/cellular/lib/python2.7/site packages/flask/ctx.py”,第178行,pop格式
%(rv,自我)
AssertionError:弹出了错误的应用程序上下文。(代替)
这开始让人觉得是一种错误的解决方案,在以后的开发中可能会出现死胡同。我曾考虑将句柄存储在文件/数据库中,但锁对象不能被pickle
有没有像我所描述的那样管理实时python对象的设计模式?对于此类任务,您最好使用
celery
(celeryproject.org)。它在生产环境中大量使用,不必担心在以后的开发中会出现死胡同。它具有管理后台任务所需的所有功能,以及更多功能。以下是操作方法。或使用rq
,我发现它比芹菜
简单10倍。如果您在那里遇到类似的问题-我发布了我的解决方案。谢谢,这正是我想要的。你应该从你的评论中做出回答。