【问题标题】:Create, manage and kill background tasks in flask app在烧瓶应用程序中创建、管理和终止后台任务
【发布时间】:2014-04-26 09:34:22
【问题描述】:

我正在构建烧瓶网络应用程序,用户可以在其中启动和管理流程。这些过程正在进行一些繁重的计算(甚至可能是几天)。在进程运行时,它会将部分结果保存到文件中以供使用。

所以当用户启动新进程时,我会生成新线程并将线程句柄保存到 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 对象的设计模式?

【问题讨论】:

  • 谢谢,这正是我想要的。您应该从您的评论中做出回答。

标签: python multithreading flask python-multithreading


【解决方案1】:

您最好使用celery (celeryproject.org) 来完成此类任务。它在生产环境中大量使用,无需担心后期开发死胡同。它拥有管理后台任务所需的一切等等。这是integrate it with flask的方法。

【讨论】:

    【解决方案2】:

    或者使用rq,我发现它比celery简单10倍。如果您在那里遇到类似的问题 - 我发布了我的解决方案 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 2014-06-26
      相关资源
      最近更新 更多