python使用celery實現異步任務執(zhí)行的例子
使用celery在django項目中實現異步發(fā)送短信
在項目的目錄下創(chuàng)建celery_tasks用于保存celery異步任務。
在celery_tasks目錄下創(chuàng)建config.py文件,用于保存celery的配置信息
```broker_url = "redis://127.0.0.1/14"```
在celery_tasks目錄下創(chuàng)建main.py文件,用于作為celery的啟動文件
from celery import Celery
# 為celery使用django配置文件進行設置
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
os.environ['DJANGO_SETTINGS_MODULE'] = 'model.settings.dev'
# 創(chuàng)建celery應用
app = Celery('model')
#導入celery配置
app.config_from_object('celery_tasks.config')
#自動注冊celery任務
app.autodiscover_tasks(['celery_tasks.sms'])
在celery_tasks目錄下創(chuàng)建sms目錄,用于放置發(fā)送短信的異步任務相關代碼。
將提供的發(fā)送短信的云通訊SDK放到celery_tasks/sms/目錄下。
在celery_tasks/sms/目錄下創(chuàng)建tasks.py(這個名字是固定的,非常重要,系統(tǒng)將會自動從這個文件中找任務隊列)文件,用于保存發(fā)送短信的異步任務
import logging
from celery_tasks.main import app
from .yuntongxun.sms import CCP
logger = logging.getLogger("django")
#驗證碼短信模板
SMS_CODE_TEMP_ID = 1
@app.task(name='send_sms_code')
def send_sms_code(mobile, code, expires):
發(fā)送短信驗證碼
:param mobile: 手機號
:param code: 驗證碼
:param expires: 有效期
:return: None
try:
ccp = CCP()
result = ccp.send_template_sms(mobile, [code, expires], SMS_CODE_TEMP_ID)
except Exception as e:
logger.error("發(fā)送驗證碼短信[異常][ mobile: %s, message: %s ]" % (mobile, e))
else:
if result == 0:
logger.info("發(fā)送驗證碼短信[正常][ mobile: %s ]" % mobile)
else:
logger.warning("發(fā)送驗證碼短信[失敗][ mobile: %s ]" % mobile)
在verifications/views.py中改寫SMSCodeView視圖,使用celery異步任務發(fā)送短信
from celery_tasks.sms import tasks as sms_tasks
class SMSCodeView(GenericAPIView):
...
# 發(fā)送短信驗證碼 這是將時間轉化為分鐘,constants.SMS_CODE_REDIS_EXPIRES 是常量
sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)
return Response({"message": "OK"})
以上這篇python使用celery實現異步任務執(zhí)行的例子就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python OpenCV的imread不能讀取中文路徑問題及解決
這篇文章主要介紹了python OpenCV的imread不能讀取中文路徑問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
Python中time.sleep(0.001)是否真的只等待1毫秒
這篇文章主要介紹了Python中time.sleep(0.001)是否真的只等待1毫秒,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06

