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

相关推荐
李广坤16 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
Sinclair17 小时前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
爱可生开源社区2 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
茶杯梦轩2 天前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
随逸1772 天前
《从零搭建NestJS项目》
数据库·typescript
海天鹰3 天前
【免费】PHP主机=域名+解析+主机
服务器
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏3 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker