How To connect Redis and Celery to Django

To connect Redis and Celery to Django, you can follow these steps:

  1. 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

  2. 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. The 6379 value is the default Redis port number, and 0 is the default Redis database number.

  3. Create a new file called celery.py in your Django project directory (the same directory as manage.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.

  4. Create a new file called __init__.py in the same directory as celery.py, and add the following code to it:

    from .celery import app as celery_app __all__ = ('celery_app',)

  5. 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.

  6. 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.

  7. 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 the tasks.py file in your app, and calls it with arguments 2 and 3. The delay method returns a AsyncResult object that you can use to check the status of the task or retrieve its result. The get 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!