Skip to main content
 首页 » 编程设计

python之无法运行本地 Celery worker,没有名为 myapp 的模块

2025年01月19日28dflying

我有一个 Django 1.11 项目,使用 Celery 3.1.25,布局如下:

env 
myproject 
    myapp 
    myotherapp 
    settings 
         settings.py 
    __init__.py 
    celery_init.py 

我的 __init__.py 包含:

from .celery_init import app as celery_app 

我的 celery_init.py 包含:

from __future__ import absolute_import 
 
import os 
import sys 
import traceback 
 
from celery import Celery 
 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') 
 
from django.conf import settings 
 
app = Celery('myproject') 
 
# Using a string here means the worker will not have to 
# pickle the object when using Windows. 
app.config_from_object('django.conf:settings') 
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) 
 
@app.task(bind=True) 
def debug_task(self): 
    print('Request: {0!r}'.format(self.request)) 

当我启动本地 Celery worker 进行开发测试时,使用:

env/bin/celery worker -A myproject -l info -n sr@%h -Q somequeue 

失败,异常:

ImportError: No module named myapp 

这是什么原因造成的?我假设这是一些路径问题,无法正确加载我的项目设置,但我没有看到我的配置有问题。我刚刚升级到 Django 1.11,这些设置在之前的版本中运行良好。我做错了什么?

我尝试在 celery_init.py 的末尾添加 print 语句,以确保它正在加载所有内容,并且每一行都没有错误地完成。

请您参考如下方法:

问题原来是 sys.path 问题以及缺少初始化 Django。工作 celery_init.py 看起来像:

from __future__ import absolute_import 
import os 
import sys 
 
from celery import Celery 
import django 
 
app = Celery('myproject') 
 
app.config_from_object('django.conf:settings', namespace='CELERY') 
 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') 
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../myproject'))) 
django.setup() 
from django.conf import settings 
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)