源代码
github: https://github.com/liaotuo/Celery.git
码云:https://gitee.com/liaotuo/Celery.git
新建Django工程
$ django-admin.py startproject django_celery
# 并新建如下文件
celery.py
tasks.py
views.py
# 目录如下:
django_celery/
├── django_celery
│ ├── celery.py
│ ├── __init__.py
│ ├── settings.py
│ ├── tasks.py
│ ├── urls.py
│ ├── views.py
│ └── wsgi.py
└── manage.py
修改settings.py
配置Broker,在最后添加
# config celery broker
BROKER_URL = 'redis://127.0.0.1:6379/0'
BROKER_TRANSPORT = 'redis'
修改celery.py
from __future__ import absolute_import
import os
import django
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_celery.settings')
django.setup()
app = Celery('django_celery')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
修改tasks.py
task 是输出雷总的经典语录 Are you OK !!!
from .celery import app
@app.task
def leijun():
print('Are you OK !!!')
修改views.py
#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from .tasks import leijun as leijun_task
def leijun(request):
leijun_task.delay()
return HttpResponse(u"[ task is running in background ]")
修改urls.py
from django.conf.urls import url
from django.contrib import admin
from django_celery import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^leijun/', views.leijun),
]
注册task
进入 django_celery根目录 执行注册命令
$ celery -A django_celery worker -l info
启动django server
python manage.py runserver
测试
# curl 请求
$ curl http://127.0.0.1:8000/leijun/
输出> [ task is running in background ]
celery 控制台输出Are you OK!!! 执行成功
备注
需要启动Redis 因为Broker 用的是redis
源代码github地址: https://github.com/liaotuo/Celery.git