Django Celery
2019-09-27 本文已影响0人
waketzheng
真不想吐槽某度,搜“Django Celery”一大堆不相关或者过时的内容。
还是官方文档靠谱:https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
来个石栗:
- 创建django项目
pip install django --user
django-admin startproject celery_test
cd celery_test
- 创建虚拟环境
pip install -U pipenv --user
pipenv --python=python3
# 更换为阿里云源
curl https://raw.githubsercontent.com/waketzheng/carstino/master/.switch_source_pipenv.py|python
pipenv shell
pipenv install --skip-lock celery django
- celery_test/celery_test/celery.py
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_test.settings')
app = Celery('celery_test')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f'Request: {request!r}')
- celery_test/celery_test/init.py
from .celery import app as celery_app
__all__ = ('celery_app',)
- rabbitmq配置:
https://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#rabbitmq
6.启动celery
celery -A celery_test worker -l info