Django使用Celery异步

安装包
python 复制代码
pip install celery

pip install eventlet 
1.在项目文件的根目录下创建目录结果
2. 在main.py文件中
python 复制代码
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     :skyTree
# version    :python 3.11
# Description:celery 主文件
"""

from celery import Celery

# 1,创建celery实例对象
celery_app = Celery('meiduo')

# 2,加载配置文件
celery_app.config_from_object('celery_tasks.config')

# 3,自动注册异步任务
celery_app.autodiscover_tasks(['celery_tasks.sms'])
3.config.py文件
python 复制代码
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     :skyTree
# version    :python 3.11
# Description:celery 配置文件
"""
# 指定任务队列的位置
broker_url = "redis://localhost:6379/0"
4.在项目后端文件下执行启动命令,即可,此时说明clery已经安装成功!
python 复制代码
# celery_tasks.main为celery包名加主文件 
celery -A celery_tasks.main worker -l info
5.在task.py文件中将发送短信的任务注册到task中必须使用装饰器并在装饰器中设置别名便于区分
python 复制代码
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     :skyTree
# version    :python 3.11
# Description:sms功能异步任务
"""
from .send_sms import Send_SMS
from ..main import celery_app


@celery_app.task(name='send_sms_code')
def send_sms_code(mobile, sms_code):
    """
    发送短信验证码的celery异步任务
    :param mobile: 手机号
    :param sms_code: 验证码
    :return:
    """
    Send_SMS().send(mobile=mobile, code=sms_code)
6.在视图函数中调用异步任务
python 复制代码
# apply_async接受的参数必须为元组或者列表
result = send_sms_code.apply_async((mobile, sms_code,))

# 使用dealy方法也可以
result = send_sms_code.dealy(mobile, sms_code)
7.执行celery启动命令

注意: 必须使用 celery -A celery_tasks.main worker -l info -P eventlet才会提示如下信息表示成功

如果使用 celery -A celery_tasks.main worker -l info命令显示如下信息,此时任务根本没有执行

相关推荐
FlightYe1 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
by209992 小时前
Linux 文件描述符与重定向
linux·服务器
橙橙笔记2 小时前
Linux基础与命令的学习
linux·运维·服务器·shell
无奈笑天下2 小时前
银河麒麟桌面操作系统【命令行配置文件与图片搜索功能】操作方法
linux·运维·服务器
飞花漫卷,情随岁迁3 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
wangxiaoxuan2174 小时前
大模型怎样调用机器人能力:目标落地、工具调用与执行反馈
数据库·机器人·php
高洁014 小时前
具身智能的人机协作与物理空间安全
人工智能·python·深度学习·机器学习·django
.道阻且长.4 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
丘山录5 小时前
本地部署 DGX Spark,200G 网卡挂在 4 条通道上
服务器·人工智能·spark·持续部署