How To connect Redis and Celery to Django
To connect Redis and Celery to Django, you can follow these steps:
-
Install the Redis and Celery packages using pip. You can do this by running the following command in your terminal or command prompt:
pip install redis celery
-
In your Django project's
settings.py
file, add the following configuration for Celery:CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
Replace
localhost
with the hostname or IP address of your Redis server if it's located on a remote machine. The6379
value is the default Redis port number, and0
is the default Redis database number. -
Create a new file called
celery.py
in your Django project directory (the same directory asmanage.py
), and add the following code to it:from celery import Celery app = Celery('your_project_name') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()
Replace
your_project_name
with the name of your Django project. -
Create a new file called
__init__.py
in the same directory ascelery.py
, and add the following code to it:from .celery import app as celery_app __all__ = ('celery_app',)
-
In your Django app's
tasks.py
file, define a task function and decorate it with the@app.task
decorator. For example:from celery import shared_task @shared_task def add(x, y): return x + y
This defines a simple task that adds two numbers together.
-
Start a Celery worker by running the following command in your terminal or command prompt:
celery -A your_project_name worker -l info
Replace
your_project_name
with the name of your Django project. -
To use the task function in your Django app code, you can import it and call it like any other Python function. For example:
from your_app.tasks import add result = add.delay(2, 3) print(result.get())
This imports the
add
task function from thetasks.py
file in your app, and calls it with arguments2
and3
. Thedelay
method returns aAsyncResult
object that you can use to check the status of the task or retrieve its result. Theget
method waits for the task to complete and returns its result.
That's it! With these steps, you should be able to use Redis and Celery to run background tasks in your Django app.
If you need assistance with your projects feel free to email me at info@airgad.com or whatsapp Jesse stay safe!