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
  'default':  { 

#  Registration djcelery Application 

# 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 

#  Use redis The 0 th database, and bind ip Port 

# 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 
def celery_test():

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 
  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(,
  url(r'^celery/', include('booktest.urls')),

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

  url(r'^celerytest/$', views.celerytest)

5 Migration to generate data tables required by celery

python migrate

6 Start redis

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

7 Start worker

python celery worker --loglevel=info

8 Open another terminal window and start the Django server

python runserver

9 Test, enter url, if 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: