The use of django celery the method of putting time consuming programs into celery for execution

  • 2021-07-18 08:15:52
  • OfStack

1 Create the project test and apply booktest in the virtual environment (procedure omitted), and then install the required packages


pip install celery==3.1.25
pip install celery-with-redis==3.0
pip install django-redis==3.1.17

2 Configure settings,


#  Database usage mysql
DATABASES = {
  'default':  { 
    'ENGINE':'django.db.backends.mysql',
    'NAME':'test',
    'USER':'root',
    'PASSWORD':'mysql',
    'HOST':'localhost',
    'PORT':3306,
  }
}

#  Registration djcelery Application 
INSTALLED_APPS = (
  ...
  'djcelery',
)

# celery Configure 

#  If an error is reported ImportError: No module named djcelery Because it is not running in a virtual environment, workon h1 Enter the virtual environment and then run the solution 
import djcelery

# Initializes all of the task Tasks, which come from booktest.task Module 
djcelery.setup_loader()

#  Use redis The 0 th database, and bind ip Port 
BROKER_URL='redis://127.0.0.1:6379/0'

# Set the initialized task source 
CELERY_IMPORTS = 'booktest.task'

3 Create the task list file task. py under the application directory booktest


from celery import task
import time

#  Plus @task Decorator, then python The function becomes 1 A celery Mission 
@task
def celery_test():
  print('hello...')
  time.sleep(5)
  print('world...')

4 Create the view and configure the relevant url configuration, and put the time-consuming task into the view to be called


#   -*- coding:utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from task import celery_test


# celery Exercise 1: Put time-consuming programs in celery Execute in 
def celerytest(request):
  # function.delay( Parameter ),celery Mission celery_test Invoke method 
  celery_test.delay()
  return HttpResponse('ok')

#  Root level url Configure  test.urls
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
  url(r'^admin/', include(admin.site.urls)),
  url(r'^celery/', include('booktest.urls')),
]

#  Under the application url Configuration b ooktest.urls
from django.conf.urls import url
import views

urlpatterns=[
  url(r'^celerytest/$', views.celerytest)
]

5 Migration to generate data tables required by celery


python manage.py migrate

6 Start redis


sudo redis-server /etc/redis/redis.conf

7 Start worker


python manage.py celery worker --loglevel=info

8 Open another terminal window and start the Django server


python manage.py runserver

9 Test, enter url, if http://127.0.0.1: 8000/celery/celerytest/, return 'ok'

At the same time, the time-consuming task program will be output in the window corresponding to worker, that is, when the user requests, the result 'ok' can be obtained without waiting too long, and the time-consuming task program is also executed asynchronously, which improves the user experience.


Related articles: