class SMSCodeView(View): """短信驗證碼""" def get(self, reqeust, mobile): """ :param reqeust: 請求對象 :param mobile: 手機號 :return: JSON """ # 1. 接收參數 image_code_client = reqeust.GET.get('image_code') uuid = reqeust.GET.get('image_code_id') # 2. 校驗參數 if not all([image_code_client, uuid]): return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺乏必傳參數'}) # 3. 建立鏈接到redis的對象 redis_conn = get_redis_connection('verify_code') # 4. 提取圖形驗證碼 image_code_server = redis_conn.get('img_%s' % uuid) if image_code_server is None: # 圖形驗證碼過時或者不存在 return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '圖形驗證碼失效'}) # 5. 刪除圖形驗證碼,避免惡意測試圖形驗證碼 try: redis_conn.delete('img_%s' % uuid) except Exception as e: logger.error(e) # 6. 對比圖形驗證碼 # bytes 轉字符串 image_code_server = image_code_server.decode() # 轉小寫後比較 if image_code_client.lower() != image_code_server.lower(): return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '輸入圖形驗證碼有誤'}) # 7. 生成短信驗證碼:生成6位數驗證碼 sms_code = '%06d' % random.randint(0, 999999) logger.info(sms_code) # 8. 保存短信驗證碼 # 短信驗證碼有效期,單位:秒 # SMS_CODE_REDIS_EXPIRES = 300 redis_conn.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code) # 9. 發送短信驗證碼 # 短信模板 # SMS_CODE_REDIS_EXPIRES // 60 = 5min # SEND_SMS_TEMPLATE_ID = 1 CCP().send_template_sms(mobile,[sms_code, 5], constants.SEND_SMS_TEMPLATE_ID) # 10. 響應結果 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '發送短信成功'})