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

相关推荐
热爱嵌入式的小许1 小时前
Linux基础项目开发1:量产工具——显示系统
linux·运维·服务器·韦东山量产工具
vvvae12343 小时前
分布式数据库
数据库
雪域迷影4 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
bug菌¹4 小时前
滚雪球学Oracle[4.2讲]:PL/SQL基础语法
数据库·oracle
逸巽散人5 小时前
SQL基础教程
数据库·sql·oracle
韩楚风5 小时前
【linux 多进程并发】linux进程状态与生命周期各阶段转换,进程状态查看分析,助力高性能优化
linux·服务器·性能优化·架构·gnu
陈苏同学5 小时前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
月空MoonSky5 小时前
Oracle中TRUNC()函数详解
数据库·sql·oracle
momo小菜pa5 小时前
【MySQL 06】表的增删查改
数据库·mysql
Pythonliu75 小时前
茴香豆 + Qwen-7B-Chat-Int8
linux·运维·服务器