簡訊驗證碼介面 阿新 • • 發佈:2021-01-08 後臺 urls.py 1 path('sms/', views.SMSViewSet.as_view({'get': 'send'})), throttles.py 123456789101112131415161718192021 from rest_framework.throttling import SimpleRateThrottlefrom django.core.cache import cachefrom django.conf import settings# 結合手機驗證碼介面來書寫classSMSRateThrottle(SimpleRateThrottle) : scope = 'sms'defget_cache_key(self, request, view):# 手機號是通過get請求提交的 mobile = request.query_params.get('mobile', None)ifnot mobile:returnNone# 不限制# 手機驗證碼傳送失敗,不限制,只有傳送成功才限制,如果需求是傳送失敗也做頻率限制,就註釋下方三行 code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})ifnot code:returnNonereturn self.cache_format % {'scope': self.scope,'ident': mobile, } const.py 12345 # 簡訊驗證碼快取keySMS_CACHE_KEY = 'sms_cache_%(mobile)s'# 簡訊驗證碼快取時間sSMS_CACHE_TIME = 300 dev.py 123456 REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'utils.exception.exception_handler', 'DEFAULT_THROTTLE_RATES' : { 'sms': '1/min' }} views.py 12345678910111213141516171819202122232425 from libs import tx_smsfrom django.core.cache import cachefrom django.conf import settingsfrom .throttles import SMSRateThrottleclassSMSViewSet(ViewSet):# 設定頻率限制,一個手機號一分鐘只能訪問一次 throttle_classes = [SMSRateThrottle] defsend(self, request, *args, **kwargs):# return APIResponse(result=False)# 1)接收前臺手機號驗證手機格式 mobile = request.query_params.get('mobile', None) if not mobile: return APIResponse(1, 'mobile field required') if not re.match(r'^1[3-9][0-9]{9}$', mobile): return APIResponse(1, 'mobile field error') # 2)後臺產生簡訊驗證碼 code = tx_sms.get_code()# 3)把驗證碼交給第三方,傳送簡訊 result = tx_sms.send_code(mobile, code, settings.SMS_CACHE_TIME // 60)# 4)如果簡訊傳送成功,伺服器快取驗證碼(記憶體資料庫),方便下一次校驗if result: cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, code, settings.SMS_CACHE_TIME)# 5)響應前臺簡訊是否發生成功return APIResponse(result=result)