Celery - Importing Models In Tasks.py
I'm having an issue getting access to models in my tasks.py My goal is to send an email at various parts of the application (user registration, reset password etc..). To do this I
Solution 1:
I found my issue. In case it helps anyone else stuck on this I needed to add the line
sys.path.append(os.path.abspath('api'))
in my celerySettings.py for models to be picked up.
so it now looks like this
from __future__ import absolute_import, unicode_literals
from django.conf import settings
import os, sys
from celery import Celery
sys.path.append(os.path.abspath('api'))
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.api.settings')
app = Celery('api', broker='amqp://')
# Using a string here means the worker doesn't have to serialize# the configuration object to child processes.# - namespace='CELERY' means all celery-related configuration keys# should have a `CELERY_` prefix.
app.config_from_object(settings, namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)defdebug_task(self):
print('Request: {0!r}'.format(self.request))
I then ran into another issue when actually trying to query the Database for my models locally. Celery was saying that my database tables did not exists, this was because it was creating a new database one folder above where the actual local database file was, to fix it I just had to change database name
"db.sqlite3"
to
os.path.join(os.path.dirname(__file__), "db.sqlite3")
in settings.py
which effectively changes it to
api/db.sqlite3
for Celery
Hopefully this helps someone else as I spent far too much time struggling this issue.
Post a Comment for "Celery - Importing Models In Tasks.py"