Reputation: 1639
I am using celery with my django project.
In the celery tasks file, I need to import my models, in order to trigger model methods. However, I would also like my model to be able to trigger certain celery tasks.
Right now I am importing my models to celery, however trying to import celery tasks into my models file results in an import loop and import error.
What is the correct way to go about this?
Upvotes: 9
Views: 3635
Reputation: 4068
Celery provides the send_task()
method, which allows to send a task by name, thus eliminating the need to import it - for example:
# models.py
from celery import current_app
# no need to import do_stuff from tasks because it will be sent by name
current_app.send_task('myapp.tasks.do_stuff', args=(1, 'two'), kwargs={'foo': 'bar'})
More in the documentation.
Upvotes: 4
Reputation: 1116
How about not using a tasks.py file and just your applying the task decorators to methods in models.py?
Upvotes: 1
Reputation: 1639
What I ended up doing, is using imports within methods, instead of a general import at the top of the models file. Obviously, i didn't really need circular imports. My problem was that I was importing the model at the top of the celery tasks file and importing the celery tasks at the top of the models file. That wasn't really necessary. by compartmentalizing the imports I was able to avoid the circular import problem
Upvotes: 9
Reputation: 4648
The general approach to solve these seeming circular dependency problems, is to factor out code that can be imported by both the models and the tasks. For example, you could factor out the model methods that you mention. Your models would import this factored out code, and so would the tasks.
Upvotes: 1