Django + celery + redis 执行异步任务及查看结果
官方文档
- https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django(配置文档)
- https://github.com/celery/celery/tree/master/examples/django(django 例子)
其他文档
- https://www.jianshu.com/p/fb3de1d9508c(celery 相关介绍)
开发环境
- python 3.6.8
- django 1.11
- celery 4.3.0
- django-celery-results 1.1.2
- django-celery-beat 1.5.0
安装 redis
安装操作 redis 库
pip install redis
(这里说明一下,pip 安装的 redis 仅仅是一个连接到 redis 缓存的一个工具;redis 服务需要自己去安装,安装文档如上)
安装 celery
pip install celery
安装 Django-celery-results
pip install django-celery-results
配置 settings.py
# 添加 djcelery APP
INSTALLED_APPS = [
# ...
'django_celery_results', # 查看 celery 执行结果
] # django 缓存
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
} # celery 定时任务
# 注意,celery4 版本后,CELERY_BROKER_URL 改为 BROKER_URL
BROKER_URL = 'redis://127.0.0.1:6379/0' # Broker 使用 Redis, 使用0数据库(暂时不是很清楚原理)
# CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' # 定时任务调度器 python manage.py celery beat
CELERYD_MAX_TASKS_PER_CHILD = 3 # 每个 worker 最多执行3个任务就会被销毁,可防止内存泄露
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # celery 结果返回,可用于跟踪结果
CELERY_RESULT_BACKEND = 'django-db' # 使用 database 作为结果存储
CELERY_CACHE_BACKEND = 'django-cache' # celery 后端缓存 # celery 内容等消息的格式设置
if os.name != "nt":
# Mac and Centos
# worker 启动命令:celery -A sqlmanager worker -l info
CELERY_ACCEPT_CONTENT = ['application/json', ]
CELERY_TASK_SERIALIZER = 'json'
# CELERY_RESULT_SERIALIZER = 'json'
else:
# windows
# pip install eventlet
# worker 启动命令:celery -A sqlmanager worker -l info -P eventlet
CELERY_ACCEPT_CONTENT = ['pickle', ]
CELERY_TASK_SERIALIZER = 'pickle'
# CELERY_RESULT_SERIALIZER = 'pickle'
生成 Django-celery-results 关联表
python manage.py migrate
python manage.py migrate
# 结果
raven.contrib.django.client.DjangoClient: 2019-12-15 21:47:10,426 /XXXXX/lib/python3.6/site-packages/raven/base.py [line:213] INFO Raven is not configured (logging is disabled). Please see the documentation for more information.
Operations to perform:
Apply all migrations: admin, auth, blog, captcha, contenttypes, django_celery_results, djcelery, logger, photo, sessions, sites, user, users
Running migrations:
Applying django_celery_results.0001_initial... OK
Applying django_celery_results.0002_add_task_name_args_kwargs... OK
Applying django_celery_results.0003_auto_20181106_1101... OK
Applying django_celery_results.0004_auto_20190516_0412... OK
Applying djcelery.0001_initial... OK
项目根目录添加 celery.py
from __future__ import absolute_import, unicode_literals
from celery import Celery
from django.conf import settings
import os # 获取当前文件夹名,即为该 Django 的项目名
project_name = os.path.split(os.path.abspath('.'))[-1]
project_settings = '%s.settings' % project_name # 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings) # 实例化 Celery
app = Celery(project_name) # 使用 django 的 settings 文件配置 celery
app.config_from_object('django.conf:settings') # Celery 加载所有注册的应用
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
配置项目根目录 __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 import pymysql pymysql.install_as_MySQLdb() __all__ = ('celery_app',)
app 目录添加 tasks.py
import json
import requests
from celery import task @task
def task_send_dd_text(url, msg, atMoblies, atAll="flase"):
body = {
"msgtype": "text",
"text": {
"content": msg
},
"at": {
"atMobiles": atMoblies,
"isAtAll": atAll
} }
headers = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
r = requests.post(url, headers=headers, data=json.dumps(body))
# print(r.text)
views.py 调用
# 假如 url 设置成 test def test(request):
# 导入
from .tasks import task_send_dd_text
# 执行
task_send_dd_text.delay(settings.DD_NOTICE_URL, "异步任务调用成功", atMoblies=["18612345678"], atAll="false")
return HttpResponse("test")
启动 celery worker
# 项目根目录终端执行(项目名称) centos or mac os:celery -A sqlmanager(项目名称) worker -l info (centos)
windows: celery -A sqlmanager(项目名称) worker -l info -P eventlet (可能还需要 pip install eventlet) # 守护进程 /root/.virtualenvs/blog/bin/celery multi start w1 -A sqlmanager(项目名称) -l info --logfile=./celerylog.log
centos7 守护 celery worker
访问调用 异步任务 的视图
http://127.0.0.1/test
Django 后台查看 celery 异步任务结果
Django + celery + redis 执行异步任务及查看结果的更多相关文章
- Django+Celery+Redis实现异步任务(发送邮件)
安装如下依赖库 pip install Celery pip install django-celery pip install django-redis 还要安装本地的Redis服务 setting ...
- Django+Celery+xadmin实现异步任务和定时任务
Django+Celery+xadmin实现异步任务和定时任务 关注公众号"轻松学编程"了解更多. 一.celery介绍 1.简介 [官网]http://www.celerypro ...
- django celery redis 定时任务
0.目的 在开发项目中,经常有一些操作时间比较长(生产环境中超过了nginx的timeout时间),或者是间隔一段时间就要执行的任务. 在这种情况下,使用celery就是一个很好的选择. cele ...
- django+celery+redis实现运行定时任务
0.目的 在开发项目中,经常有一些操作时间比较长(生产环境中超过了nginx的timeout时间),或者是间隔一段时间就要执行的任务. 在这种情况下,使用celery就是一个很好的选择. cele ...
- django+celery+redis环境搭建
初次尝试搭建django+celery+redis环境,记录下来,慢慢学习~ 1.安装apache 下载httpd-2.0.63.tar.gz,解压tar zxvf httpd-2.0.63.tar. ...
- Celery+redis实现异步
目录 Celery+redis实现异步 安装redis 安装celery-with-redis 添加celery相关配置 创建异步运行任务tasks.py 启动 Celery+redis实现异步 安装 ...
- 06: django+celery+redis
目录: 1.1 Celery介绍 1.2 celery 组件 1.3 安装相关包 与 管理命令 1.4 celery与Django执行异步任务 1.5 在django中使用计划任务功能 1.1 Cel ...
- 项目部署Django+celery+redis
celery介绍 1.celery应用举例 1.Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以 ...
- django+celery+redis应用
一.celery介绍 1.应用场景 a. Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理,如果你的业务场景中需要用到异步任务,就可以考虑使用ce ...
- Django+Celery+redis kombu.exceptions.EncodeError:Object of type is not JSON serializable报错
在本文中例子中遇到问题的各种开发版本如下: Python3.6.8 Django==2.2 celery==4.4.0 kombu==4.6.7 redis==3.3.0 大概的报错如下截图: 是在开 ...
随机推荐
- 安装Hadoop单节点伪分布式集群
目录 安装Hadoop单节点伪分布式集群 系统准备 开启SSH 安装JDK 安装Hadoop 下载 准备启动 伪分布式模式安装 配置 配饰SSH免密登录本机 测试启动 单节点安装YARN 伪分布式集群 ...
- 聊聊Spring注解@Transactional失效的那些事
一.前言 emm,又又又踩坑啦.这次的需求主要是对逾期计算的需求任务进行优化,现有的计算任务运行时间太长了.简单描述下此次的问题:在项目中进行多个数据库执行操作时,我们期望的是将其整个封装成一个事务, ...
- GaussDB技术解读丨高级压缩
本文作者|华为云数据库GaussDB首席架构师 冯柯 [背景介绍] 数据压缩与关系数据库的结合,早已不是一个新鲜的话题,当前我们已经看到了各种各样数据库压缩的产品和解决方案.对于GaussDB来说,在 ...
- 利用InnoStep在VS编译时自动构建安装包
摘要 很多同学在C/S开发领域或多或少都可能会遇到需要制作安装包的场景,打包的工具也是五花八门,例如有NSIS.InstallShield.Wix Toolset.ClickOnce等等,这里以Inn ...
- Ubuntu16.04配置NTP时间同步
环境 查看系统版本:lsb_release -a 名词解释 PDT是指太平洋夏令时(Pacific Daylight Time),是美国西部地区和加拿大的一部分地区使用的时区.它位于UTC-7和UTC ...
- study the docker network of macvlan
Introduce: 在 Macvlan 出现之前,我们只能为一块以太网卡添加多个 IP 地址,却不能添加多个 MAC 地址,因为 MAC 地址正是通过其全球唯一性来标识一块以太网卡的,即便你使用了创 ...
- Uncaught TypeError: Failed to set the 'currentTime' property on 'HTMLMediaElement': The provided double value is non-finite.
musicSeekTo: function(value){this.audio.currentTime = this.audio.duration*value; }, musicVoiceSeekTo ...
- .NET周刊【8月第1期 2023-08-06】
国内文章 NativeBuferring,一种零分配的数据类型(上篇) https://www.cnblogs.com/artech/p/17586781.html 之前一个项目涉及到针对海量(千万级 ...
- module.exports和exports,应该用哪个
在 Node.js 编程中,模块是独立的功能单元,可以在项目间共享和重用.作为开发人员,模块让我们的生活更轻松,因为我们可以使用模块来增强应用程序的功能,而无需亲自编写.它们还允许我们组织和解耦代码, ...
- 响应式编程——初识 Flux 和 Mono
by emanjusaka from https://www.emanjusaka.top/archives/4 彼岸花开可奈何 本文欢迎分享与聚合,全文转载请留下原文地址. 前言 Reactor ...