I'm using django 1.3 with celery. I followed the instruction in http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html but old version django project structure is different, and it complains KeyError, below is the demo project myproj structure

.
├── app1
│   ├── __init__.py
│   ├── models.py
│   ├── tasks.py
│   ├── tests.py
│   ├── views.py
├── __init__.py
├── manage.py
├── mycelery.py
├── settings.py
├── urls.py

When I send a task from the web, it failed KeyError: 'myproj.app1.tasks.add'. However it's ok when I send a task from python manage.py shell

>>> from app1.tasks import add
>>> result = add.apply_async(args=[1,2], countdown=30)
>>> result.ready() #wait for 30 seconds
True
>>> result.get()
3

Here is my code https://gist.github.com/dengshuan/a4adc7b690e101da0520

  • in your example, it should be tasks not task. – levi Sep 2 '14 at 1:48
  • yes, i just corrected it – cbsw Sep 2 '14 at 1:52

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) will register tasks in app1 directory as app1.tasks.add, tasks sent from shell will generate task with the same name. But tasks from web generates task named as myproj.app1.tasks.add. So it complains KeyError.

Changing from tasks import add to from app1.tasks import add solves the problem.

And if we follow this guide http://celery.readthedocs.org/en/latest/userguide/tasks.html#automatic-naming-and-relative-imports , it fails with ImportError. This is because old django project structure. We should

  1. change app = Celery('myproj', backend='redis://localhost', broker='redis://localhost:6379/0') to app = Celery('myproj', backend='redis://localhost', broker='redis://localhost:6379/0', include=['myproj.app1.tasks'])
  2. comment out app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
  3. add project directory to celery sys.path.append(os.path.abspath(os.pardir))

All these problems come from different task names from server and client side. We should make sure they are the same

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.