【问题标题】:flask to execute other tasks after return render_template烧瓶返回渲染模板后执行其他任务
【发布时间】:2016-11-16 00:59:59
【问题描述】:

在烧瓶应用程序中,我需要在执行return render_template(page) 后执行其他任务的checkJob 功能(检查作业状态和电子邮件给用户)。用户将看到确认页面,但仍有后台作业正在运行以检查作业状态。

我尝试将 celery https://blog.miguelgrinberg.com/post/using-celery-with-flask 用于后台作业,但它不起作用。 return render_template(page) 之后的任何内容都不会被执行。

代码片段如下:

@app.route("/myprocess", methods=['POST'])
def myprocess():
    //.... do work
    #r = checkJob()
    return render_template('confirm.html')
    r = checkJob()

@celery.task()
def checkJob():
    bb=1
    while bb == 1:
       print "checkJob"
       time.sleep(10)

【问题讨论】:

  • 你不能在return 之后运行任何东西,因为return 结束(每个)函数,它会立即离开函数。您必须在 return 之前使用 checkJob.delay()
  • 谢谢@furas。我尝试将 checkJob.delay() 放在 return 语句之前,但问题是没有显示 confirm.html 并等待 checkJob 完成。有没有办法可以立即显示 confirm.html 然后执行 checkJob 任务?非常感谢!!
  • 如我所见,您还没有尝试使用 Celery。
  • 谢谢@Sergey。你怎么知道我没有使用 Celery?你能告诉我我犯了什么错误吗?我按照blog.miguelgrinberg.com/post/using-celery-with-flask 中的示例进行操作
  • 如果您阅读了那篇文章,为什么不使用 .delay().apply_async() 调用 celery 任务?

标签: python flask celery celery-task


【解决方案1】:

按照 cmets 中的建议,您应该使用 apply_async()

@app.route("/myprocess", methods=['POST'])
def myprocess():
    #.... do work
    r = checkJob.apply_async()
    return render_template('confirm.html')

请注意,与example 一样,您不想调用checkJob(),而是将其保留为checkJob

【讨论】:

  • 我已经尝试过这样做,但仍然没有在 checkJob 中执行任何操作。我们的例子是@celery.task,而不是@celery.task(),我也试过了,但什么也没做@celery.task() def checkJob(): bb=1 while bb == 1: print "checkJob" time.sleep(10)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
相关资源
最近更新 更多