首页 > 技术文章 > 18-短信验证码接口

borntodie 2021-02-22 16:31 原文

短信验证码接口

user/throttles.py

from rest_framework.throttling import SimpleRateThrottle

class SmsThrottling(SimpleRateThrottle):
	scope = 'sms'
	def get_cache_key(self, request, view):
		# 获取手机号码并校验是否符合格式
		telephone = request.query_params.get('telephone')
		# cache_format = 'throttle_%(scope)s_%(ident)s'
		return self.cache_format%{'scope':self.scope,'ident':telephone}

settings/dev.py

# drf配置
REST_FRAMEWORK = {
	# 自定义短信发送频率配置
	'DEFAULT_THROTTLE_RATES': {
		'sms': '1/m'  # key要跟类中的scop对应
	}
}

user/views.py

class SendSmsView(ViewSet):
	throttle_classes = (SmsThrottling,)

	# 发送短信验证码接口视图
	@action(methods=('GET',), detail=False)
	def send(self, request, *args, **kwargs):

		# 获取手机号码并校验是否符合格式
		telephone = request.query_params.get('telephone')
		if not re.match('^1[3-9][0-9]{9}$', telephone):  # 当电话号码格式不正确
			return APIResponse(code=0, msg='Error', result='号码格式不正确!')

		# 获取随机验证码,因为没有腾讯短信,所以这里就手动生成验证码
		code = get_code()
		print("当前验证码是:", code)
		# 发送手机短信
		result = send_message(telephone, code)
		if result:  # 这是发送成功
			# 发送验证码成功后,需要将验证码保存起来,方便后期登录使用
			# cache(缓存的键,缓存的值,缓存保存时间),这里验证码先不存缓存
			cache.set(settings.PYTHON_CACHE_KEY.format(telephone), code, 180)
			return APIResponse(code=1, msg='Successful', result='验证发送成功')
		else:  # 这是发送失败
			return APIResponse(code=0, msg='Error', result='您操作太频繁了,验证发送失败')

user.urls.py

from django.urls import path, include
from rest_framework.routers import SimpleRouter
from . import views

router = SimpleRouter()
router.register('', views.SendSmsView, 'send')  # 此处第一个参数不要加上,因为视图类中使用了actions,会把该视图名添加进来

urlpatterns = [
	path('', include(router.urls)),
]

推荐阅读