python - flask 在返回 render_template 后执行其他任务

标签 python flask celery celery-task

在 flask 应用程序中,我需要在执行 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)

最佳答案

正如评论中所建议的,您应该使用apply_async()

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

请注意,与 example 一样,您不想调用 checkJob() 而是保持它像 checkJob 一样。

关于python - flask 在返回 render_template 后执行其他任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622366/

相关文章:

python - 假设随机抽样

python - 在 Windows 上获取本地时区名称(Python 3.9 zoneinfo)

python-rq Queue.job_ids 始终为空

python - 如何在不同的机器上设置 celery worker ?

django - 是否可以在 Celery 任务中运行 VACUUM 命令?

python - 可以从代码中将 IPDB/Celery-RDB 堆栈跟踪 ('where' )打印到标准输出吗?

python - Mac 操作系统 : python packages failed to build because of gcc issues

python - Blobstore 上传处理程序时 Google App Engine 中的编码问题

python - 如何在 flask-sqlalchemy 中按索引创建顺序

python - 使用 HTML 模板在 python 中发送电子邮件