前言: 针对高延时任务, 直接在一次网络请求中处理完毕会导致很不好的体验, celery则可以不阻塞请求后台处理这些任务, 并且可以使用django的models进行数据库操作.
环境
python models:
- celery-4.1.1
- redis-2.10.6
- django-1.11.7
其他:
- redis-3.2.9
- macos
- python3.6
创建django工程
django-admin startproject dc
cd dc
django-admin startapp main
此时项目结构如下
dc
|-- __init__.py
|-- main
| |-- __init__.py
| |-- admin.py
| |-- apps.py
| |-- migrations
| | `-- __init__.py
| |-- models.py
| |-- tests.py
| `-- views.py
|-- settings.py
|-- urls.py
`-- wsgi.py
修改settings.py
, 添加app
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','dc.main' //new added
]
修改dc/main/models.py
, 创建新models
from django.db import models# Create your models here.class Person(models.Model):first_name = models.CharField(max_length=30)last_name = models.CharField(max_length=30)
创建根访问节点
dc/main/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.def hello(request):return HttpResponse('hello world')
dc/urls.py
urlpatterns = [url(r'^admin/', admin.site.urls),url(r'^$', hello) //new added
]
依次执行以下语句, 初始化django各功能模块
python manage.py migrate
python manage.py makemigrations main
python manage.py sqlmigrate main 0001
python manage.py migrate
接下来python manage.py runserver
, 访问http://127.0.0.1:8000
即可看到hello world.
启动redis
redis是作为celery中间件使用的, 用来存储消息队列.
redis解压后, 直接运行src/redis-server
即可启动, 默认端口6379
配置celery
参考文档
创建dc/celery.py
#-*- coding:utf-8 -*-import os
from celery import Celery# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dc.settings')app = Celery('dc')# 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()
修改 dc/__init__.py
from .celery import app as celery_app__all__ = ['celery_app']
修改 dc/settings.py
, 设定 redis URL
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/3'
创建dc/main/tasks.py
#-*- coding:utf-8 -*-from celery import shared_task@shared_task
def test():import timetime.sleep(5)from dc.main.models import Personperson = Person(first_name='smith', last_name='jhon')person.save()c = Person.objects.count()print(f'person count is {c}')
修改dc/main/views.py
def hello(request):from dc.main.tasks import testtest.delay()return HttpResponse('hello world')
启动celery进程
celery -A dc worker -l info
接下来访问http://127.0.0.1:8000
, 即可发现页面立刻返回, 并没有被time阻塞, 查看启动celery的窗口, 即可发现log以及打印的信息, 确定models可以正常使用.
おわり.