Django Celery异步任务队列的实现


Posted in Python onJuly 24, 2019

背景

在开发中,我们常常会遇到一些耗时任务,举个例子:

上传并解析一个 1w 条数据的 Excel 文件,最后持久化至数据库。

在我的程序中,这个任务耗时大约 6s,对于用户来说,6s 的等待已经是个灾难了。

比较好的处理方式是:

  1. 接收这个任务的请求
  2. 将这个任务添加到队列中
  3. 立即返回「操作成功,正在后台处理」的字样
  4. 后台消费这个队列,执行这个任务

我们按照这个思路,借助 Celery 进行实现。

实现

本文所使用的环境如下:

  • Python 3.6.7
  • RabbitMQ 3.8
  • Celery 4.3

使用 Docker 安装 RabbitMQ

Celery 依赖一个消息后端,可选方案有 RabbitMQ, Redis 等,本文选用 RabbitMQ 。

同时为了安装方便,RabbitMQ 我直接使用 Docker 安装:

docker run -d --name anno-rabbit -p 5672:5672 rabbitmq:3

启动成功后,即可通过 amqp://localhost 访问该消息队列。

安装并配置 Celery

Celery 是 Python 实现的工具,安装可以直接通过 Pip 完成:

pip install celery

同时假设当前我的项目文件夹为 proj ,项目名为 myproj ,应用名为 myapp

安装完成后,在 proj/myproj/ 路径下创建一个 celery.py 文件,用来初始化 Celery 实例:

proj/myproj/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery, platforms

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings')

app = Celery('myproj',
       broker='amqp://localhost//',
       backend='amqp://localhost//')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.s
# - 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()

然后在 proj/myproj/__init__.py 中添加对 Celery 对象的引用,确保 Django 启动后能够初始化 Celery:

proj/myproj/__init__.py

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

无其他特殊配置的话,Celery 的基本配置就是这些。

编写一个耗时任务

为了模拟一个耗时任务,我们直接创建一个方法,使其「睡」10s ,并将其设置为 Celery 的任务:

proj/myapp/tasks.py

import time
from myproj.celery import app as celery_app

@celery_app.task
def waste_time():
  time.sleep(10)
  return "Run function 'waste_time' finished."

启动 Celery Worker

Celery 配置完成,并且任务创建成功后,我们以异步任务的模式启动 Celery :

celery -A myproj worker -l info

注意到我强调了异步模式,是因为 Celery 除了支持异步任务,还支持定时任务,因此启动时候要指明。

同时要注意,Celery 一旦启动,对 Task(此处为 waste_time) 的修改必须重启 Celery 才会生效。

任务调用

在请求处理的逻辑代码中,调用上面创建好的任务:

proj/myapp/views.py

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .tasks import waste_time

@require_http_methods(["POST"])
def upload_files(request):
  waste_time.delay()
  # Status code 202: Accepted, 表示异步任务已接受,可能还在处理中
  return JsonResponse({"results": "操作成功,正在上传,请稍候..."}, status=202)

调用 waste_time.delay() 方法后, waste_time 会被加入到任务队列中,等待空闲的 Celery Worker 调用。

效果

当我们发送请求时,这个接口会直接返回 {"results": "操作成功,正在上传,请稍候..."} 的响应内容而非卡住十秒,用户体验要好许多。

总结

用 Celery 处理这种异步任务是 Python 常用的方法,虽然实际执行成功耗时不变甚至有所增加(如 Worker 繁忙导致处理滞后),但是对于用户体验来说更容易接受,点击上传大文件后可以继续处理其他事务,而不需要在页面等待。
Celery 还有更多用法本文未介绍到,其文档已经非常详尽,有需要可直接参考。

参考

http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

https://hub.docker.com/_/rabbitmq

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中文分词实现方法(安装pymmseg)
Jun 14 Python
浅谈python类属性的访问、设置和删除方法
Jul 25 Python
Python编程实现输入某年某月某日计算出这一天是该年第几天的方法
Apr 18 Python
利用numpy+matplotlib绘图的基本操作教程
May 03 Python
Python编程之string相关操作实例详解
Jul 22 Python
Python中read()、readline()和readlines()三者间的区别和用法
Jul 30 Python
win10下python3.5.2和tensorflow安装环境搭建教程
Sep 19 Python
python列表推导式操作解析
Nov 26 Python
Django3.0 异步通信初体验(小结)
Dec 04 Python
Python批量启动多线程代码实例
Feb 18 Python
Python实现随机爬山算法
Jan 29 Python
在前女友婚礼上,用Python破解了现场的WIFI还把名称改成了
May 28 Python
python如何统计代码运行的时长
Jul 24 #Python
Django时区详解
Jul 24 #Python
详解Django定时任务模块设计与实践
Jul 24 #Python
Python3中urlencode和urldecode的用法详解
Jul 23 #Python
对python3中的RE(正则表达式)-详细总结
Jul 23 #Python
python正则表达式匹配不包含某几个字符的字符串方法
Jul 23 #Python
python使用百度文字识别功能方法详解
Jul 23 #Python
You might like
一个ftp类(ini.php)
2006/10/09 PHP
解析php函数method_exists()与is_callable()的区别
2013/06/21 PHP
php生成txt文件标题及内容的方法
2014/01/16 PHP
PHP7之Mongodb API使用详解
2015/12/26 PHP
laravel中命名路由的使用方法
2017/02/24 PHP
php json相关函数用法示例
2017/03/28 PHP
PHP时间类完整代码实例
2021/02/26 PHP
Code:loadScript( )加载js的功能函数
2007/02/02 Javascript
jquery获取input表单值的代码
2010/04/19 Javascript
再论Javascript下字符串连接的性能
2011/03/05 Javascript
jQuery.prototype.init选择器构造函数源码思路分析
2013/02/05 Javascript
JavaScript实现GriwView单列全选(自写代码)
2013/05/13 Javascript
三种方式获取XMLHttpRequest对象
2014/04/21 Javascript
node.js中的require使用详解
2014/12/15 Javascript
JavaScript给url网址进行encode编码的方法
2015/03/18 Javascript
学习Angularjs分页指令
2016/07/01 Javascript
JavaScript无操作后屏保功能的实现方法
2017/07/04 Javascript
解决ztree搜索中多级菜单展示不全问题
2017/07/05 Javascript
Node.js dgram模块实现UDP通信示例代码
2017/09/26 Javascript
js中apply()和call()的区别与用法实例分析
2018/08/14 Javascript
如何基于javascript实现贪吃蛇游戏
2020/02/09 Javascript
vue父子组件间引用之$parent、$children
2020/05/20 Javascript
python实现博客文章爬虫示例
2014/02/26 Python
wxpython学习笔记(推荐查看)
2014/06/09 Python
Python做简单的字符串匹配详解
2017/03/21 Python
Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例
2018/02/13 Python
详解Python用户登录接口的方法
2019/04/17 Python
python 梯度法求解函数极值的实例
2019/07/10 Python
浅谈pandas.cut与pandas.qcut的使用方法及区别
2020/03/03 Python
Python多线程通信queue队列用法实例分析
2020/03/24 Python
Python 实现二叉查找树的示例代码
2020/12/21 Python
提供世界各地便宜的机票:Sky-tours
2016/07/21 全球购物
丝芙兰中国官方商城:SEPHORA中国
2018/01/10 全球购物
荷兰领先的百货商店:De Bijenkorf
2018/10/17 全球购物
信用社员工先进事迹材料
2014/02/04 职场文书
使用python将HTML转换为PDF pdfkit包(wkhtmltopdf) 的使用方法
2022/04/21 Python