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命令显示如下信息,此时任务根本没有执行

相关推荐
辞旧 lekkk1 天前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
2301_809204701 天前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277771 天前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
笨蛋不要掉眼泪1 天前
Mysql架构揭秘:update语句的执行流程
数据库·mysql·架构
万邦科技Lafite1 天前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
疯狂成瘾者1 天前
服务器的单体和集群
运维·服务器
秋91 天前
ruoyi项目更换为mysql9.7.0数据库
数据库
Andya_net1 天前
MySQL | MySQL 8.0 权限管理实践-精确赋予库、表只读等权限
android·数据库·mysql
筑梦之路1 天前
harbor数据库报错权限异常如何处理——筑梦之路
数据库·harbor
czlczl200209251 天前
理解 MySQL 行锁:两阶段锁协议与热点更新优化
数据库·mysql