1. 程式人生 > 實用技巧 >簡訊驗證碼介面

簡訊驗證碼介面

後臺

urls.py
1
path('sms/', views.SMSViewSet.as_view({'get': 'send'})),
throttles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from rest_framework.throttling import SimpleRateThrottle
from django.core.cache import cache
from 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:
returnNone

return
self.cache_format % {

'scope': self.scope,
'ident': mobile,
}
const.py
1
2
3
4
5
# 簡訊驗證碼快取key
SMS_CACHE_KEY = 'sms_cache_%(mobile)s'

# 簡訊驗證碼快取時間s
SMS_CACHE_TIME = 300
dev.py
1
2
3
4
5
6
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
'DEFAULT_THROTTLE_RATES'
: {

'sms': '1/min'
}
}
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from libs import tx_sms
from django.core.cache import cache
from django.conf import settings
from .throttles import SMSRateThrottle
classSMSViewSet(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)