關於Java構造器初始化
阿新 • • 發佈:2020-10-07
1.註冊容聯雲賬號
1.1 註冊賬號
https://www.yuntongxun.com/user/login
1.2 登入即可看到開發者賬號資訊
1.3 新增測試賬號
'''1. 安裝容聯雲sdk''' pip install ronglian_sms_sdk # 免費測試文件地址:https://doc.yuntongxun.com/p/5a531a353b8496dd00dcdfe2 '''2. 簡訊傳送程式碼''' # libs/rl_sms.py from ronglian_sms_sdk import SmsSDK accId = '8a216da8747ac98201749c0de38723b7' accToken = '86072b540b4648229b27400414150ef2' appId = '8a216da8747ac98201749c0de45123be' def send_message(phone, datas): sdk = SmsSDK(accId, accToken, appId) tid = '1' # 測試模板id為: 1. 內容為: 【雲通訊】您的驗證碼是{1},請於{2}分鐘內正確輸 入。 # mobile = '13303479527' # datas = ('666777', '5') # 模板中的引數按照位置傳遞resp = sdk.sendMessage(tid, phone, datas) return resp
3.在檢視函式中使用
3.1 在verifications/urls.py中新增路由
urlpatterns = [ path('sms_codes/', views.SmsCodeView.as_view()), ]
3.2 寫試圖函式
# verifications/views.py from rest_framework.permissions import AllowAny from rest_framework.views import APIViewfrom rest_framework.response import Response import re import random from utils.rl_sms import send_message class SmsCodeView(APIView): # 1. 所有人可以訪問 permission_classes = (AllowAny,) def post(self, request): # 1. 獲取引數 phone = request.data.get('phone') image_code = request.data.get('image_code') image_code_uuid = request.data.get('image_code_uuid') # 2. 檢查引數 if not all([phone, image_code, image_code_uuid]): return Response({"code": 999, "msg": "引數不全"}) if not re.match(r'^1[3456789]\d{9}$', phone): return Response({"code": 999, "msg": "手機號碼不正確"}) # 3. 檢查是否傳送 redis_client = get_redis_connection('img_code') phone_exists = redis_client.get(phone) if phone_exists: return Response({"code": 999, "msg": "頻繁傳送, 請稍後再試"}) redis_image_code = redis_client.get(image_code_uuid) # bytes if redis_image_code: # bytes 轉成 string redis_image_code = redis_image_code.decode() # 比較使用者提供的圖片內容是否和redis中儲存的一致 if image_code.upper() != redis_image_code: return Response({'code': 999, 'msg': '圖片驗證碼不正確'}) # 4. 傳送 code = '%06d' % random.randint(0, 999999) # 隨機6位驗證碼 send_resp = send_message(phone, (code, "5")) # 5.1 儲存code 到 redis中 # redis_client.setex(phone, 60 * 5, code) # phone:code, 5分鐘有效期 # 5.2 從redis中刪除這個圖片驗證碼, 以防再次被使用 # redis_client.delete(image_code_uuid) # 5.3 使用 pipeline 批量操作 pl = redis_client.pipeline() pl.setex(phone, 60 * 5, code) pl.delete(image_code_uuid) pl.execute() # 6. 返回結果 return Response({"code": 0, "msg": "簡訊傳送成功"})