Django with Celery

 

img

Celery

Django project structure:

- proj/
  - manage.py
  - requirements.txt
  - proj/
    - __init__.py
    - settings.py
    - urls.py
    - wsgi.py
    - celery.py
  - app1/
  	- __init__.py
  	- models.py
  	- views.py
  	- tasks.py

contents of proj/proj/celery.py:

# Celery Module 
# https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#django-first-steps 
import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('proj')

# 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('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django apps.
app.autodiscover_tasks()


@app.task(bind=True, ignore_result=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

contents of proj/proj/__init__.py:

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
# https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#django-first-steps 

from .celery import app as celery_app

__all__ = ('celery_app',)