今天小編就為大家分享一篇python使用celery實作異步任務執行的例子,具有很好的參考價值,希望對大家有所幫助。一起跟随小編過來看看吧
使用celery在django項目中實作異步發送短信
在項目的目錄下建立celery_tasks用于儲存celery異步任務。
在celery_tasks目錄下建立config.py檔案,用于儲存celery的配置資訊
```broker_url = "redis://127.0.0.1/14"```
在celery_tasks目錄下建立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'
# 建立celery應用
app = Celery('model')
#導入celery配置
app.config_from_object('celery_tasks.config')
#自動注冊celery任務
app.autodiscover_tasks(['celery_tasks.sms'])
在celery_tasks目錄下建立sms目錄,用于放置發送短信的異步任務相關代碼。
将提供的發送短信的雲通訊SDK放到celery_tasks/sms/目錄下。
在celery_tasks/sms/目錄下建立tasks.py(這個名字是固定的,非常重要,系統将會自動從這個檔案中找任務隊列)檔案,用于儲存發送短信的異步任務
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):
發送短信驗證碼
: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("發送驗證碼短信[異常][ mobile: %s, message: %s ]" % (mobile, e))
else:
if result == 0:
logger.info("發送驗證碼短信[正常][ mobile: %s ]" % mobile)
else:
logger.warning("發送驗證碼短信[失敗][ mobile: %s ]" % mobile)
在verifications/views.py中改寫SMSCodeView視圖,使用celery異步任務發送短信
from celery_tasks.sms import tasks as sms_tasks
class SMSCodeView(GenericAPIView):
...
# 發送短信驗證碼 這是将時間轉化為分鐘,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實作異步任務執行的例子就是小編分享給大家的全部内容了
推薦我們的python學習基地,點選進入,看老程式是如何學習的!從基礎的python腳本、爬蟲、django、資料挖掘等程式設計技術,工作經驗,還有前輩精心為學習python的小夥伴整理零基礎到項目實戰的資料,!每天都有程式員定時講解Python技術,分享一些學習的方法和需要留意的小細節