首先得安裝倆個表要包
pip install celery pip install celery-with-redis
如果 'namespace=‘CELERY''出現報錯 celery可以適當降一下級別 ‘4.4.7'
from __future__ import absolute_import, unicode_literals import os from celery import Celery # 設置環境變量 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'md.settings') # 注冊Celery的APP app = Celery('meiduo') # 綁定配置文件 app.config_from_object('django.conf:settings', namespace='CELERY') # 自動發現各個app下的tasks.py文件 # app.autodiscover_tasks()
#獲取redis連接 def getRedis(): from django_redis import get_redis_connection conn = get_redis_connection() return conn #發短信 去容聯云官網查找自己的信息 from ronglian_sms_sdk import SmsSDK accId = 'ACCOUNT SID(主賬號ID)' accToken = 'AUTH TOKEN(賬戶授權令牌)' appId = 'AppID(默認)' import json def send_message(mobile,code,time): sdk = SmsSDK(accId, accToken, appId) tid = '1' datas = (code, time) resp = sdk.sendMessage(tid, mobile, datas) result = json.loads(resp) if result['statusCode'] == '000000': return 1 return 2
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/' CELERY_RESULT_SERIALIZER = 'json'
from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app']
# 寫異步任務的地方 from celery.task import task from .comm import send_message # 定義發送手機號的方法 @task def mail(mobile,code,time): send_message(mobile,code,time)
如果用了redis數據庫,得先開啟數據庫
from utils.task import send_message from utils.comm import getRedis import random class SendMes(APIView): # 短信驗證 def get(self,request): # 接收客戶端發送的數據 imagecode = request.query_params.get('imagecode') print(imagecode) mobile = request.query_params.get('mobile') print(mobile) uuid = request.query_params.get('uuid') print(uuid) if not all([imagecode,mobile]): return Response({'msg':'沒有獲取到'}) # 驗證圖片驗證碼 conn =getRedis() # redis 中取驗證碼 code = conn.get(uuid) print(code) if code: code = str(code,encoding='utf8') # 圖片驗證碼對比 if imagecode.lower() == code.lower(): # 驗證通過后調用發送短信接口 sms_code = random.randint(10000,99999) # 引用comm文件中的send_message result = send_message(mobile,sms_code,1) # 加入短信嗎發送成功 if result: # redis中要存短信驗證嗎 conn.setex(mobile,60,sms_code) # 把圖片驗證碼從redis中刪除 conn.delete(uuid) return Response({'msg':sms_code}) else: return ({'msg':'發送失敗'}) else: return Response({'msg':'驗證碼不正確'}) return Response('ok')
然后另開終端 cd到項目 目錄下啟動celery 服務
指定并發數 --autoscale(最多,最少)
celery worker -A 項目的文件名 --loglevel=info --pool=solo --autoscale=50,5 urn Response('ok') ~~~ #### 3.7.先啟動django項目 然后另開終端 cd到項目 目錄下啟動celery 服務 指定并發數 --autoscale(最多,最少) ```pyhon celery worker -A 項目的文件名 --loglevel=info --pool=solo --autoscale=50,5
到此這篇關于使用Celery 容聯云 異步發送驗證碼的文章就介紹到這了,更多相關Celery異步發送驗證碼內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
標簽:銀川 呼倫貝爾 三亞 湘西 呼倫貝爾 葫蘆島 烏魯木齊 安慶
巨人網絡通訊聲明:本文標題《python中使用Celery容聯云異步發送驗證碼功能》,本文關鍵詞 python,中,使用,Celery,容聯,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。