Using celery in Django projects


Official reference…

be careful: Celery 4.0 supports Django 1.8 and later. For Django before 1.8, use celery 3.1.

1、 Installation

pip install celery

2、 Project structure

-- proj/
  -- proj/
  -- myapp/

3、 Use steps

First step

stayproj/proj/New nextcelery.pyModule, write the following code:

import os

Step 2

stayproj/proj/__init__.pyImport the module created above under the file. The code is as follows:

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ['celery_app']

Step 3

staymyapp/Create your own task module, write the task function and@shared_taskDecoration, code as follows:

from __future__ import absolute_import, unicode_literals
from celery import shared_task

def async_func():

Step 4

Store the task execution results. This step can be ignored if it is unnecessary.

  • installdjango-celery-resultslibrary
pip install django-celery-results
  • add todjango-celery-resultsTo projectsettingsin
  • Perform database migration to create a cellry data table
python migrate django_celery_results
  • Configuring the use of celerydjango_celery_resultsback-end

    'celery': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'celery_cache',

Step 5

Initiate the asynchronous task start command in the view function

# proj/proj/

Step 6

Start the celery worker process

celery -A proj worker -l info

This work adoptsCC agreement, reprint must indicate the author and the link to this article