1. 程式人生 > 程式設計 >python使用celery實現非同步任務執行的例子

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實現非同步任務執行的例子就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。