Skip to content

Commit

Permalink
Fixes loader so DB connection is not closed for eager tasks.
Browse files Browse the repository at this point in the history
Closes celery#116.
  • Loading branch information
mlavin authored and ask committed Apr 12, 2012
1 parent 0bdaca8 commit 6dcfc6f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 deletions.
9 changes: 7 additions & 2 deletions djcelery/loaders.py
Expand Up @@ -87,9 +87,14 @@ def on_process_cleanup(self):
self.close_database()
self.close_cache()

def on_task_init(self, *args, **kwargs):
def on_task_init(self, task_id, task):
"""Called before every task."""
self.close_database()
try:
is_eager = task.request.is_eager
except AttributeError:
is_eager = False
if not is_eager:
self.close_database()

def on_worker_init(self):
"""Called when the worker starts.
Expand Down
4 changes: 3 additions & 1 deletion tests/someapp/models.py
@@ -1,3 +1,5 @@
from django.db import models # noqa

# Create your models here.

class Thing(models.Model):
name = models.CharField(max_length=10)
9 changes: 9 additions & 0 deletions tests/someapp/tasks.py
@@ -1,6 +1,15 @@
from celery.task import task

from django.db.models import get_model


@task(name="c.unittest.SomeAppTask")
def SomeAppTask(**kwargs):
return 42


@task(name="c.unittest.SomeModelTask")
def SomeModelTask(pk):
model = get_model("someapp", "Thing")
thing = model.objects.get(pk=pk)
return thing.name
22 changes: 22 additions & 0 deletions tests/someapp/tests.py
@@ -0,0 +1,22 @@
from __future__ import absolute_import

from django.test.testcases import TestCase as DjangoTestCase

from someapp.models import Thing
from someapp.tasks import SomeModelTask


class SimpleTest(DjangoTestCase):

def setUp(self):
self.thing = Thing.objects.create(name=u"Foo")

def test_apply_task(self):
"Apply task function."
result = SomeModelTask.apply(kwargs={'pk': self.thing.pk})
self.assertEqual(result.get(), self.thing.name)

def test_task_function(self):
"Run task function."
result = SomeModelTask(pk=self.thing.pk)
self.assertEqual(result, self.thing.name)

0 comments on commit 6dcfc6f

Please sign in to comment.