Skip to main content
 首页 » 编程设计

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

2025年02月15日25xing901022

在 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 一样。