情景:用户发起request,并等待response返回。在本些views中,可能须要执行一段耗时的程序,那么用户就会等待很长时间,形成很差的用户体验,好比发送邮件、手机验证码等。html
使用celery后,状况就不同了。解决:将耗时的程序放到celery中执行。python
celery官方网站: href="http://www.celeryproject.org/web
celery中文文档: href="http://docs.jinkan.org/docs/celery/redis
celery名词:django
示例中使用到的安装包版本浏览器
celery==3.1.25 django-celery==3.1.17
1)在应用question_help/views.py文件中建立视图sayhello。服务器
import time def sayhello(request): print('hello ...') time.sleep(2) print('world ...') return HttpResponse("hello world")
2)在question_help/urls.py中配置。函数
url(r'^sayhello$',views.sayhello),
3)启动服务器,在浏览器中输入以下网址:网站
http://127.0.0.1:8000/sayhello/
4)在终端中效果,两次输出之间等待一段时间才会返回结果。url
5)在settings.py中注册celery应用
INSTALLED_APPS = ( ... 'djcelery', }
6)在settings.py文件中配置代理和任务模块。
import djcelery djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/2'
7)在应用question_help/目录下建立tasks.py文件。
import time from celery import task @task def sayhello(): print('hello ...') time.sleep(2) print('world ...')
8)打开question_help/views.py文件,修改sayhello视图以下:
from booktest import tasks ... def sayhello(request): # print('hello ...') # time.sleep(2) # print('world ...') tasks.sayhello.delay() return HttpResponse("hello world")
9)执行迁移生成celery须要的数据表。
python manage.py migrate
生成表以下:
10)启动Redis,若是已经启动则不须要启动。
sudo service redis start
11)启动worker。
python manage.py celery worker --loglevel=info
启动成功后提示以下图:
11)打开新终端,进入虚拟环境,启动服务器,刷新浏览器。 在旧终端中两个输出间仍有时间间隔。
运行完成后以下图,注意两个终端中的时间,服务器的响应是当即返回的。