djangocelerydjango-celerydjcelery

Celery : prevent working for same name function without delay


I'm using Redis and Celery together for django project.

[Pre-Condition]

django==1.5.4
Redis==2.2.4
Celery==3.0.23
django-redis==3.7.1
django-celery==3.0.23

[Directory Structure]

Project/
     apps/
         app_1/
             views.py
                 def get_something():
         utils/
             redis.py
                 def do_stuff(): // do something related with Redis
             tasks.py
                 @task()
                 def do_stuff(): // execute do_stuff() at redis.py

[Problem]

In views.py,

from utils.redis import do_stuff
from utils.tasks import do_stuff


def get_something():

    do_stuff.delay()  => Execute task by celery (Normal)

    do_stuff()        => Executed do_stuff from tasks.py, not from redis.py
                         Making a recursion error (Unusual)
                         Expected to execute do_stuff from redis.py

How can I handle Celery to execute only by "delay method" when function name overlapped.

Thanks in advance.


Solution

  • You can't have two identical names pointing at different things in any Python code, for obvious reasons. You can more easily distinguish between them by importing the module rather than the function:

    from utils import redis
    from utils import tasks
    
    
    def get_something():
        redis.do_stuff.delay()
        tasks.do_stuff()
    

    But also note that you can call Celery tasks directly without using delay(), which causes them to be executed immediately in-process rather than through Celery.