Using celery in Django projects

Time:2021-8-14

Official reference documentsdocs.celeryproject.org/en/stable/d…

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/
  -- manage.py
  -- proj/
      -- __init__.py
      -- settings.py
      -- urls.py
  -- myapp/
    -- __init__.py
    -- apps.py
    -- views.py
    -- models.py

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 undertasks.py, write the task function and@shared_taskDecoration, code as follows:

from __future__ import absolute_import, unicode_literals
from celery import shared_task

@shared_task
def async_func():
    pass

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
INSTALLED_APPS = (
    ...,
    'django_celery_results',
)
  • Perform database migration to create a cellry data table
python manage.py migrate django_celery_results
  • Configuring the use of celerydjango_celery_resultsback-end
CELERY_CACHE_BACKEND = 'celery'

CACHES = {
    '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/views.py

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