CODE - Python How To Use Celery and RabbitMQ With Django
CODE - Python How To Use Celery and RabbitMQ With Django
(useful-python-tricks.html)
(django-best-practices-models-design.html)
(python-simple-tricks-to-level-up-your-python-coding.html)
(python-pandas-tips-to-make-data-analysis-faster.html)
(create-custom-django-management-commands.html)
(setup-ssl-certificate-on-nginx-for-django-application.html)
Python - How to Use Celery
and RabbitMQ with Django
(use-celery-with-django.html)
(use-jwt-authentication-with-django-rest-framework.html)
(django-tips-for-designing-better-models.html)
(django-query-prefetch-related.html)
(django-tips-for-working-with-databases.html)
(adding-additional-field-to-modelserializer.html)
(how-to-Implement-dependent-chained-dropdown-list-with-django.html)
To work with Celery, we also need to install RabbitMQ because Celery requires
an external solution to send and receive messages. Those solutions are called
message brokers. Currently, Celery supports RabbitMQ, Redis, and Amazon
SQS as message broker solutions.
Table of Contents
Why Should I Use Celery?
Installation
Installing RabbitMQ on Ubuntu 16.04
Installing RabbitMQ on Mac
Installing RabbitMQ on Windows and Other OSs
Celery Basic Setup
Creating Our First Celery Task
Starting The Worker Process
Managing The Worker Process in Production with Supervisord
Further Reading
Ideally this request and response cycle should be fast, otherwise we would
leave the user waiting for way too long. And even worse, our Web server can
only serve a certain number of users at a time. So, if this process is slow, it can
limit the amount of pages your application can serve at a time.
For the most part we can work around this issue using cache, optimizing
database queries, and so on. But there are some cases that theres no other
option: the heavy work have to be done. A report page, export of big amount of
data, video/image processing are a few examples of cases where you may
want to use Celery.
We don’t use Celery through the whole project, but only for specific tasks that
are time-consuming. The idea here is to respond to the user as quick as
possible, and pass the time-consuming tasks to the queue so to be executed
in the background, and always keep the server ready to respond to new
requests.
Installation
The easiest way to install Celery is using pip:
The RabbitMQ scripts are installed into /usr/local/sbin . You can add it to your
.bash_profile or .profile .
vim ~/.bash_profile
export PATH=$PATH:/usr/local/sbin
Now you can start the RabbitMQ server using the following command:
rabbitmq-server
Celery Basic Setup
First, consider the following Django project named mysite with an app named
core:
mysite/
|-- mysite/
| |-- core/
| | |-- migrations/
| | |-- templates/
| | |-- apps.py
| | |-- models.py
| | +-- views.py
| |-- templates/
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| +-- wsgi.py
|-- manage.py
+-- requirements.txt
settings.py
CELERY_BROKER_URL = 'amqp://localhost'
Alongside with the settings.py and urls.py files, let’s create a new file named
celery.py.
celery.py
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
app = Celery('mysite')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
__init__.py
__all__ = ['celery_app']
This will make sure our Celery app is important every time Django starts.
Just for testing purpose, let’s create a Celery task that generates a number of
random User accounts.
core/tasks.py
import string
@shared_task
def create_random_user_accounts(total):
for i in range(total):
username = 'user_{}'.format(get_random_string(10, string.ascii_lette
rs))
email = '{}@example.com'.format(username)
password = get_random_string(50)
User.objects.create_user(username=username, email=email, password=pa
ssword)
return '{} random users created with success!'.format(total)
@shared_task
def name_of_your_function(optional_param):
pass # do something heavy
forms.py
class GenerateRandomUserForm(forms.Form):
total = forms.IntegerField(
validators=[
MinValueValidator(50),
MaxValueValidator(500)
]
)
This form expects a positive integer field between 50 and 500. It looks like this:
Then my view:
views.py
class GenerateRandomUserView(FormView):
template_name = 'core/generate_random_users.html'
form_class = GenerateRandomUserForm
create_random_user_accounts.delay(total)
Instead of calling the create_random_user_accounts directly, I’m calling
create_random_user_accounts.delay() . This way we are instructing Celery to
execute this function in the background.
But before you try it, check the next section to learn how to start the Celery
worker process.
Change mysite to the name of your project. The result is something like this:
Now we can test it. I submitted 500 in my form to create 500 random users.
Then after a few seconds, if we refresh the page, the users are there:
If we check the Celery Worker Process again, we can see it completed the
execution:
[program:mysite-celery]
command=/home/mysite/bin/celery worker -A mysite --loglevel=INFO
directory=/home/mysite/mysite
user=nobody
numprocs=1
stdout_logfile=/home/mysite/logs/celery.log
stderr_logfile=/home/mysite/logs/celery.log
autostart=true
autorestart=true
startsecs=10
stopasgroup=true
Python Standard
Library - Learn the
Hidden Gems
Ad pythonstandardlibrarybook.c…
Angularjs - Create a
Real-Time App with
Socket.IO, Angular,…
designmycodes.com
CODE - ReactJS
Environment Setup
designmycodes.com
CODE - Vuejs
Tutorial With
Example From…
designmycodes.com
Company
Home (../index.html)
About Us (../about.html)
Privacy Policy (../privacy-policy.html)
Follow us on
FACEBOOK (HTTPS://WWW.FACEBOOK.COM/DESIGNMYCODE-287393808601218/?REF=NF&HC_REF=