ImportError:没有名为celery的模块

时间:2018-02-23 22:43:30

标签: python django celery

我按照this tutorial尝试使用我的Django项目运行定期任务。

但是,尝试使用以下命令运行Celery工作程序时:

celery -A myproject worker -l info

我收到以下错误:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named celery

我怀疑这可能是因为我的设置文件(local.py和production.py)不符合标准的Django文件结构,它们嵌套在一个较低的文件夹中。

├── myproject
│   ├── myproject
│   │   ├── __init__.py
│   │   ├── settings
│   │   │   ├── __init__.py
│   │   │   ├── base.py
│   │   │   ├── celery.py
│   │   │   ├── local.py
│   │   │   ├── production.py
│   ├── manage.py

__初始化__。PY

# myproject/myproject/settings/__init__.py

from __future__ import absolute_import, unicode_literals

from .base import *

try:
    from .local import *
    live = False
except: 
    live = True

if live:
    from .production import *

from .celery import app as celery_app

celery.py

# myproject/myproject/settings/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.local')

app = Celery('myproject')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
  print('Request: {0!r}'.format(self.request))



from celery.schedules import crontab
app.conf.beat_schedule = {
    'add-every-minute-contrab': {
        'task': 'fetch_news',
        'schedule': crontab()
    }
}

绝对安装了芹菜。

我已经看过很多关于这个错误的其他帖子,但没有一个帮助过。任何建议都将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

通过将以下内容添加到上面目录中的__init__.py来管理以进行修复。

# myproject/myproject/__init__.py

from __future__ import absolute_import

from myproject.settings.celery import app as celery_app 

答案 1 :(得分:0)

为什么使用?:

from .celery import app as celery_app

您正在尝试从同一文件夹导入模块#myproject / myproject / settings / 改为使用:

 from celery import app as celery_app