安裝包
pip install celery
pip install eventlet
1.在項目文件的根目錄下創(chuàng)建目錄結(jié)果
2. 在main.py文件中
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# Author :skyTree
# version :python 3.11
# Description:celery 主文件
"""
from celery import Celery
# 1,創(chuàng)建celery實例對象
celery_app = Celery('meiduo')
# 2,加載配置文件
celery_app.config_from_object('celery_tasks.config')
# 3,自動注冊異步任務(wù)
celery_app.autodiscover_tasks(['celery_tasks.sms'])
?3.config.py文件
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# Author :skyTree
# version :python 3.11
# Description:celery 配置文件
"""
# 指定任務(wù)隊列的位置
broker_url = "redis://localhost:6379/0"
4.在項目后端文件下執(zhí)行啟動命令,即可,此時說明clery已經(jīng)安裝成功!
# celery_tasks.main為celery包名加主文件
celery -A celery_tasks.main worker -l info
5.在task.py文件中將發(fā)送短信的任務(wù)注冊到task中必須使用裝飾器并在裝飾器中設(shè)置別名便于區(qū)分
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# Author :skyTree
# version :python 3.11
# Description:sms功能異步任務(wù)
"""
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):
"""
發(fā)送短信驗證碼的celery異步任務(wù)
:param mobile: 手機號
:param sms_code: 驗證碼
:return:
"""
Send_SMS().send(mobile=mobile, code=sms_code)
6.在視圖函數(shù)中調(diào)用異步任務(wù)
# apply_async接受的參數(shù)必須為元組或者列表
result = send_sms_code.apply_async((mobile, sms_code,))
# 使用dealy方法也可以
result = send_sms_code.dealy(mobile, sms_code)
7.執(zhí)行celery啟動命令
注意: 必須使用?celery -A celery_tasks.main worker -l info -P eventlet?才會提示如下信息表示成功
如果使用?celery -A celery_tasks.main worker -l info 命令顯示如下信息,此時任務(wù)根本沒有執(zhí)行文章來源:http://www.zghlxwxcb.cn/news/detail-835341.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-835341.html
到了這里,關(guān)于Django使用Celery異步的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!