How to Use Celery and RabbitMQ with Django

How to Use Celery and RabbitMQ with Django

How to Use Celery and RabbitMQ with Django .Celeryis a very asynchronous job queues trong. It is a very good replacement for `contab`cLinux. Django is Pythons best framework?

Celeryis a very asynchronous job queues trong. It is a very good replacement for contabcLinux. Django is Python's best framework?

About? Celery and Django? documents, you can follow:

Celery: Django:

This is image title


Celery 4.0Already supports Django 1.8 and newer versions. For older versions of Django, should use Celery 3.1.

Setup simple Django project

Perform basic Django project creation using the following command:

% mkdir celery-simple
% cd celery-simple
% virtualenv venv -p python3
Running virtualenv with interpreter /Users/minhhahao/.pyenv/versions/3.6.2/bin/python3
Using base prefix '/Users/minhhahao/.pyenv/versions/3.6.2'
New python executable in /Users/minhhahao/workspace/celery-simple/venv/bin/python3
Also creating executable in /Users/minhhahao/workspace/celery-simple/venv/bin/python
Installing setuptools, pip, wheel...done.
% source venv/bin/activatele
(venv) % pip install django==1.9 celery==4.0
Collecting django==1.9
  Downloading (6.6MB)
    100% |████████████████████████████████| 6.6MB 2.2MB/s
Collecting celery==4.0
  Downloading (395kB)
    100% |████████████████████████████████| 399kB 2.2MB/s
Collecting pytz>dev (from celery==4.0)
  Downloading (510kB)
    100% |████████████████████████████████| 512kB 9.6MB/s
Collecting billiard<3.6.0,>= (from celery==4.0)
  Downloading (89kB)
    100% |████████████████████████████████| 92kB 7.8MB/s
Collecting kombu<5.0,>=4.0 (from celery==4.0)
  Downloading (181kB)
    100% |████████████████████████████████| 184kB 8.6MB/s
Collecting amqp<3.0,>=2.1.4 (from kombu<5.0,>=4.0->celery==4.0)
  Downloading (48kB)
    100% |████████████████████████████████| 51kB 15.6MB/s
Collecting vine>=1.1.3 (from amqp<3.0,>=2.1.4->kombu<5.0,>=4.0->celery==4.0)
Installing collected packages: django, pytz, billiard, vine, amqp, kombu, celery
Successfully installed amqp-2.2.2 billiard- celery-4.0.0 django-1.9 kombu-4.1.0 pytz-2018.4 vine-1.1.4
(venv) % django-admin startproject simple
(venv) % cd simple
(venv) % python startapp ce

Simple project structure:

(venv) % tree
├── ce
│   ├──
│   ├──
│   ├──
│   ├── migrations
│   │   └──
│   ├──
│   ├──
│   └──
└── simple
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   └── settings.cpython-36.pyc

4 directories, 14 files

After creating, I created a print print "Hello? World!" on the web:

# simple/
# Application definition

# simple/
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^', include('ce.urls'))

# ce/
# Create new file `ce/` to define url of app ce
from django.conf.urls import url
from ce import views

urlpatterns = [
    url(r'^$', views.index),

# ce/
# Define view
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World!")

Run server!

(venv) % python runserver                                                                     
Performing system checks...

System check identified no issues (0 silenced).

May 03, 2018 - 02:22:31
Django version 1.9, using settings 'simple.settings'
Starting development server at
Quit the server with CONTROL-C.

Setup a simple celery task

To run Celeryyou need to set up a Redis server or RabbitMQ server. And they are definitely installed

With Redisserver:

# simple/
REDIS_HOST = 'localhost'
REDIS_PORT = '6379'
BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0'

With RabbitMQserver:

# simple/
BROKER_URL = 'amqp://guest:[email protected]:5672/' 

OK, next I create a file to define Celery instance ?:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

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

app = Celery('simple')

# 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 app configs.

def debug_task(self):
    print('Request: {0!r}'.format(self.request))

Then, import task into simple/

# simple/
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

Next, will I create a print task timenow each time the page loads?HelloWorld!. I created a file ce/ The project structure looks like:

(venv) % tree
├── ce
│   ├──
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── admin.cpython-36.pyc
│   │   ├── models.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── views.cpython-36.pyc
│   ├──
│   ├──
│   ├── migrations
│   │   ├──
│   │   └── __pycache__
│   │       └── __init__.cpython-36.pyc
│   ├──
│   ├──
│   ├──
│   ├──
│   └──
├── db.sqlite3
└── simple
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   ├── celery.cpython-36.pyc
    │   ├── settings.cpython-36.pyc
    │   ├── urls.cpython-36.pyc
    │   └── wsgi.cpython-36.pyc

6 directories, 27 files

Modify file

# ce/
# Create your tasks here
from celery import shared_task

def add(x, y):
    return x + y

def mul(x, y):
    return x * y

def xsum(numbers):
    return sum(numbers)

To use a combination of Djangoand CeleryI use the django-celery-resultsextension

(venv) % pip install django-celery-results
Collecting django-celery-results
Requirement already satisfied: celery<5.0,>=4.0 in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from django-celery-results) (4.0.0)
Requirement already satisfied: billiard<3.6.0,>= in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from celery<5.0,>=4.0->django-celery-results) (
Requirement already satisfied: kombu<5.0,>=4.0 in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from celery<5.0,>=4.0->django-celery-results) (4.1.0)
Requirement already satisfied: pytz>dev in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from celery<5.0,>=4.0->django-celery-results) (2018.4)
Requirement already satisfied: amqp<3.0,>=2.1.4 in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from kombu<5.0,>=4.0->celery<5.0,>=4.0->django-celery-results) (2.2.2)
Requirement already satisfied: vine>=1.1.3 in /Users/minhhahao/workspace/celery-simple/venv/lib/python3.6/site-packages (from amqp<3.0,>=2.1.4->kombu<5.0,>=4.0->celery<5.0,>=4.0->django-celery-results) (1.1.4)
Installing collected packages: django-celery-results
Successfully installed django-celery-results-1.0.1

Add django_celery_resultss into simple/settings/.py

# simple/

Run task:

% celery -A simple worker -l info -B                                                               

[email protected] v4.0.0 (latentcall)

Darwin-16.7.0-x86_64-i386-64bit 2018-05-03 03:33:01

.> app:         simple:0x1035f6ba8
.> transport:   amqp://guest:**@localhost:5672//
.> results:
.> concurrency: 8 (prefork)
.> task events: OFF (enable -E to monitor tasks in this worker)

.> celery           exchange=celery(direct) key=celery

  . simple.celery.debug_task -> This task defined

[2018-05-03 03:33:01,752: INFO/Beat] beat: Starting...
[2018-05-03 03:33:03,053: INFO/MainProcess] Connected to amqp://guest:**@
[2018-05-03 03:33:03,065: INFO/MainProcess] mingle: searching for neighbors
[2018-05-03 03:33:04,085: INFO/MainProcess] mingle: all alone
/Users/minhhahao/.pyenv/versions/3.5.2/lib/python3.5/site-packages/celery/fixups/ UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!
  warnings.warn('Using settings.DEBUG leads to a memory leak, never '

[2018-05-03 03:33:04,107: WARNING/MainProcess] /Users/minhhahao/.pyenv/versions/3.5.2/lib/python3.5/site-packages/celery/fixups/ UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments!
  warnings.warn('Using settings.DEBUG leads to a memory leak, never '

[2018-05-03 03:33:04,107: INFO/MainProcess] [email protected] ready.

That's basically it !!!


Sometimes there will be compatibility errors: python, celery, django. Here, I use Python 3.5.2, Celery 4.0, Django 1.9. You need to choose the correct version to avoid errors.

To run? Celerythen you need to make sure? setup Redisor RabbitMQserver to run Asynchronous Thanks for reading!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Django Tutorial | Django Course

🔥Intellipaat Django course: 👉This Python Django tutorial will help you learn what is django web development &...

Developing Restful APIs with Python, Django and Django Rest Framework

This article is a definitive guide for starters who want to develop projects with RESTful APIs using Python, Django and Django Rest Framework.