Skip to content

Cannot access Django ORM in worker when using python3+eventlet #2829

Closed

Description

@imaia

Hello folks; I have a setup with:

  • gunicorn
  • django 1.8.4
  • celery==3.1.18
  • django-celery==3.1.16 (django db backend)
  • sqlite (dev)
  • eventlet==0.17.4

And when I try to access my database from within a worker task, (Model.objects.stuff()), I get the following error:

django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140124131096384 and th

The thing is, I've found through the internet that I should explicitly monkey_patch my project to make things work. The suggestion was to have the code below in my manage.py:

import eventlet
import eventlet.debug

os.environ["EVENTLET_NOPATCH"] = 'True'
eventlet.monkey_patch()
eventlet.debug.hub_prevent_multiple_readers(False)

As documentation mentions no further configuration for using eventlet besides informing that you want to use it to the worker, and I'm not quite sure what EVENTLET_NOPATCH and the event.debug.hub... stuff do, I'm here to ask what is a good way to make celery+django+models+eventlet work.

By the way, my worker is invoked like this, from upstart:

exec python manage.py celery worker --pidfile=/path/to/prj.pid --settings=$SETTINGS --pool=eventlet -c 100 -Ofair --events --logfile=/path/to/logs.log

[EDITED]
Found the link https://joshbohde.com/blog/async-workers-in-django-with-celery

Activity

  1. ask commented on Dec 12, 2015

    @ask
    Contributor

    If you use manage.py then the patching happens to late to patch everything, so you will have mysterious problems.

    The solution is to move into using the new Celery+Django project layout, using celery -A proj worker instead of manage.py, or patching manage.py as you write there.

    It's not necessary to set the EVENTLET_NOPATCH environment variable, as there is no danger
    in calling monkey_patch multiple times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions