python celery 无效值 -A 无法加载应用程序

问题描述

我有以下项目目录:

azima:
    __init.py
    main.py
    tasks.py

任务.py

from .main import app

@app.task
def add(x,y):
    return x + y

@app.task
def mul(x,y):
    return x * y

@app.task
def xsum(numbers):
    return sum(numbers)

main.py

from celery import Celery

app = Celery('azima',backend='redis://localhost:6379/0',broker='redis://localhost:6379/0',include=['azima.tasks'])

# Optional configuration,see the application user guide.
app.conf.update(
    result_expires=3600,)

if __name__ == '__main__':
    app.start()

当我运行一个命令来初始化 celery worker 时,我收到这个错误

(azima_venv) brightseid@darkseid:~$ celery -A azima worker -l INFO
Usage: celery [OPTIONS] COMMAND [ARGS]...

Error: Invalid value for '-A' / '--app': 
Unable to load celery application.
Module 'azima' has no attribute 'celery'

但是当我像之前那样将 main.py 重命名celery.py 时,没有问题。

在这里遗漏了什么?

解决方法

有两种方法

  1. 将您的 app 导入到 azima/__init__.py
from azima.main import app
    
celery = app  # you can omit this line

你可以省略最后一行,celery 会从导入中识别 celery 应用程序。然后你调用 celery -A azima worker -l INFO

  1. celery -A azima.main worker -l INFO一样称呼您的应用程序