芹菜任务在Flask应用程序运行后在后台运行两次,为什么?

2024-05-17 03:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个Flask web应用程序,我希望在Flask应用程序运行后启动一些异步后台任务。我一直在阅读有关烧瓶和芹菜的示例和手册,例如here,但在许多示例中,芹菜后台任务绑定到烧瓶路由函数。也就是说,当从客户端接收到对特定URL绑定Flask函数的请求时,芹菜后台函数将运行

除此之外,我还希望在Flask应用程序运行时启动芹菜后台任务。我在这篇文章中创建了一个简单的工作示例(myapp.py,Flask+芹菜+RabbitMQ):

from flask import Flask
from celery import Celery
import time

app = Flask(__name__)

celery = Celery(app.name, backend='rpc://', broker='pyamqp://')

@celery.task
def long_background_task1():
    print("Doing the heavy background job 1...")
    time.sleep(5)
    print("Finished the heavy background job 1!")
    return("This is the return from the heavy background job 1!")

@celery.task
def long_background_task2():
    print("Doing the heavy background job 2...")
    time.sleep(10)
    print("Finished the heavy background job 2!")
    return("This is the return from the heavy background job 2!")


@app.route("/")
def index():
    return("This is the index page")


if __name__ == '__main__':
    # At the start of the Flask application, start also one or more background Celery tasks
    long_background_task1.delay()
    long_background_task2.delay()
    app.run(debug=True)

因此,当运行myapp.py时,我希望启动芹菜任务long_background_task1long_background_task2,并在后台运行。如果我使用以下命令启动终端中的芹菜工人:

celery -A myapp.celery worker --loglevel=INFO

我得到以下输出:

enter image description here

所以芹菜看起来不错!接下来,当我运行myapp.py时,我在芹菜终端中获得以下输出(单击要放大的图像):

enter image description here

因此芹菜任务确实是在后台启动的,但它们运行了两次!这是什么原因

所以我的问题是:如何让芹菜后台任务只在后台启动一次?


Tags: thefromappflaskreturnjobmyapplong
1条回答
网友
1楼 · 发布于 2024-05-17 03:20:56

我想我自己找到了解决办法。我在这里查看:

https://www.reddit.com/r/flask/comments/2chlio/does_init_get_run_twice_in_my_case/

我注意到这样的评论:

“开发服务器会执行生产中不会发生的所有操作,以确保将对文件的更改加载到应用程序中。”

所以我在myapp.py中改变了:

app.run(debug=True)

app.run(debug=False)

问题解决了!不再运行两次任务

相关问题 更多 >