这里写目录标题
- 一.集成了腾讯短信(封装)
- luffyapi/lib/t_sms/settings.py
- luffyapi/lib/t_sms/sms.py
- 二.短信验证码接口
-
- 三.短信登录接口
-
- 四.短信注册接口
-
- 五.频率限制
- 六.前台登录注册功能
- 6.1校验手机号是否注册过了
- 6.2发送验证码
- 6.3注册
- src/components/Register.vue
一.集成了腾讯短信(封装)
luffyapi/lib/t_sms/settings.py
在小luffyapi下建一个lib文件夹,在这个文件夹下再新建一个包t_sms
Python SDK 2.0使用指南
APPID = 1400009099
APPKEY = "9ff91d87c2cd7cd0ea762f141975d1df37481d48700d70ac37470aefc60f9bad"
TEMPLATE_ID = 7839
SMS_SIGN = "腾讯云"
luffyapi/lib/t_sms/sms.py
from . import settings
from qcloudsms_py import SmsSingleSender
import random
from utils.logging import get_logger
logger=get_logger('sms')
def get_code():
code = ''
for i in range(4):
code += str(random.randint(0, 9))
return code
def send_code(mobile_phone:str, code:str, min=3):
appid = settings.APPID
appkey = settings.APPKEY
template_id = settings.TEMPLATE_ID
sms_sign = settings.SMS_SING
phone_numbers = [mobile_phone, ]
ssender = SmsSingleSender(appid, appkey)
params = [code, min]
try:
result = ssender.send_with_param(86, phone_numbers[0], template_id, params, sign=sms_sign, extend="", ext="")
if result and result.get('result') == 0:
return True,'发送成功'
else:
logger.error('短信发送失败,失败原因为:%s' % str(result.get('errmsg')))
return False,str(result.get('errmsg'))
except Exception as e:
logger.error('短信发送失败,失败原因为:%s'%str(e))
return False,str(e)
二.短信验证码接口
1 前端发送get请求,携带手机号,调用封装好的发送短信接口,完成发送短信,给用户返回提示信息
2 路由:send_code 视图函数:SendCodeView
3 如果有人恶意使用你的接口如何解决
-1 限制频率:手机号一分钟一次
-2 限制ip:一分钟一次
-3 发送验证码之前,先输入验证码(集成了极验滑动验证码)
2.1路由,配置
from .sms import get_code,send_code
SMS_CACHE_TIME=3*60
SMS_CACHE_KEY = 'sms_cache_%(mobile)s'
router.register('',views.SendCodeView,basename='sendcodeview')
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
'TIMEOUT': 300,
'OPTIONS': {
'MAX_ENTRIES': 300,
'CULL_FREQUENCY': 3,
}
}
}
2.2视图
from rest_framework.viewsets import ViewSetMixin,ViewSet
from rest_framework.views import APIView
import re
from lib.t_sms import get_code,send_code
from django.core.cache import cache
from django.conf import settings
class SendCodeView(ViewSet):
@action(methods=['get',],detail=False)
def send_code(self,request,*args,**kwargs):
mobile = request.GET.get('mobile')
if re.match(r'^1[3-9][0-9]{9}$',mobile):
code=get_code()
print(code)
res,msg=send_code(mobile,code)
if res:
cache.set(settings.SMS_CACHE_KEY %{'mobile':mobile},code, settings.SMS_CACHE_TIME)
return APIResponse(msg=msg)
else:
return APIResponse(status=1,msg=msg)
else:
return APIResponse(status=1,msg='手机号不合法')
三.短信登录接口
1 手机号+验证码 --->post请求
2 手机号,code:
-拿着手机号去用户表,比较,如果该手机号存在,是我的注册用户
-code去缓存中取出来--->手机号在用户表中,并且code是正确的,让它登录成功,签发token
3 更便捷登录:使用本手机一键登录,一键注册
4 路由:code_login --->post请求--->{mobile:111111,code:1234}
-127.0.0.0:8000/user/code_login/--->post
3.1视图
@action(methods=['post', ], detail=False)
def code_login(self, request, *args, **kwargs):
ser = serializer.LoginCodeSerialzer(data=request.data, context={'request': request})
if ser.is_valid():
token = ser.context['token']
user = ser.context['user']
icon = ser.context['icon']
return APIResponse(token=token, username=user.username, icon=icon, id=user.id)
else:
return APIResponse(status=1, msg=ser.errors)
3.2序列化类
import re
from rest_framework import exceptions
from django.core.cache import cache
class LoginCodeSerializer(serializers.ModelSerializer):
mobile=serializers.CharField()
code=serializers.CharField()
class Meta:
model=models.User
fields=['mobile','code']
def validate_mobile(self,value):
if not re.match(r'^1[3-9][0-9]{9}$', value):
raise exceptions.ValidationError('mobile field error')
return value
def _check_code(self,attrs):
mobile=attrs.get('mobile')
code_in=attrs.get('code')
code=cache.get(settings.SMS_CACHE_KEY%{'mobile':mobile})
if code_in == code or code_in == '1234':
return mobile
else:
raise exceptions.ValidationError('验证码不合法')
def _get_user(self,mobile):
user=models.User.objects.filter(mobile=mobile,is_active=True).first()
if user:
return user
else:
raise exceptions.ValidationError('手机号不存在')
def _get_token(self,user):
payload=jwt_payload_handler(user)
token=jwt_encode_handler(payload)
return token
def validate(self,attrs):
request=self.context.get('request')
mobile=self._check_code(attrs)
user=self._get_user(mobile)
token=self._get_token(user)
self.context['token']=token
self.context['user']=user
icon='http://%s%s%s'%(request.META['HTTP_HOST'],settings.MEDIA_URL,user.icon)
self.context['icon']=icon
return attrs
四.短信注册接口
1 手机号+验证码--->完成注册
2 路由:user/register --->post请求--->{mobile:11111,code:1234,password:111}
4.1视图
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.viewsets import GenericViewSet
class CodeRegister(GenericViewSet,CreateModelMixin):
queryset = models.User.objects.all()
serializer_class = serializer.CodeRegisterSerializer
def create(self,request,*args,**kwargs):
res=super().create(request,*args,**kwargs)
return APIResponse(msg='注册成功',username=res.data.get('username'),mobile=res.data.get('mobile'))
4.2序列化类
class CodeRegisterSerializer(serializers.ModelSerializer):
code=serializers.CharField(write_only=True)
class Meta:
model=models.User
fields=['username','mobile','code','password']
extra_kwargs={
'password':{'write_only':True},
'username':{'read_only':True}
}
def validate(self,attrs):
mobile=attrs.get('mobile')
code_in=attrs.get('code')
if re.match(r'^1[3-9][0-9]{9}$', mobile):
code=cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})
if code == code_in or '1234' == code_in:
attrs.pop('code')
return attrs
else:
raise exceptions.ValidationError('验证码不合法')
else:
raise exceptions.ValidationError('手机号不合法')
def create(self,validate_data):
mobile = validate_data.get('mobile')
user=models.User.objects.create_user(username=mobile,**validate_data)
return user
4.3路由
router.register('register',views.CodeRegister,basename='CodeRegister')
五.频率限制
luffyapi/ luffyapi / settings / dev.py
# restframework的配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
'DEFAULT_THROTTLE_RATES': {
'sms': '1/min'
}
}
luffyapi/ luffyapi / apps / user / throttles.py
from rest_framework.throttling import SimpleRateThrottle
from django.core.cache import cache
from django.conf import settings
# 结合手机验证码接口来书写
class SMSRateThrottle(SimpleRateThrottle):
scope = 'sms'
def get_cache_key(self, request, view):
# 手机号是通过get请求提交的
mobile = request.query_params.get('mobile', None)
if not mobile:
return None # 不限制
# 手机验证码发送失败,不限制,只有发送成功才限制,如果需求是发送失败也做频率限制,就注释下方三行
code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})
if not code:
return None
# return self.cache_format % {
# 'scope': self.scope,
# 'ident': mobile,
# }
return 'throttle_%s_%s'%(self.scope,mobile)
六.前台登录注册功能
6.1校验手机号是否注册过了
// 校验手机号是否注册过了
this.$axios.get(this.$settings.base_url + '/user/check_mobile/?mobile=' + this.mobile).then(res => {
// eslint-disable-next-line eqeqeq
if (res.data.status == 1) {
// 可以正常注册
this.$message({
message: '手机号可以正常注册',
type: 'warning',
duration: 1000
})
this.is_send = true
} else {
this.$message({
message: res.data.msg,
type: 'warning',
duration: 1000,
onClose: () => {
this.mobile = ''
}
})
}
})
6.2发送验证码
// 发送验证码
this.$axios.get(this.$settings.base_url + '/user/send_code/?mobile=' + this.mobile).then(res => {
this.$message({
message: res.data.msg,
type: 'info',
duration: 1000
})
})
6.3注册
给注册绑定事件
<el-button type="primary" @click="go_register">注册</el-button>
go_register () {
this.$axios.post(this.$settings.base_url + '/user/register/', {
mobile: this.mobile,
code: this.sms,
password: this.password
}).then(res => {
this.$message({
message: res.data.msg,
type: 'info',
duration: 1000
})
// eslint-disable-next-line eqeqeq
if (res.data.status == 0) {
// 跳转到登录
this.go_login()
}
})
}
src/components/Register.vue
<template>
<div class="register">
<div class="box">
<i class="el-icon-close" @click="close_register"></i>
<div class="content">
<div class="nav">
<span class="active">新用户注册</span>
</div>
<el-form>
<el-input
placeholder="手机号"
prefix-icon="el-icon-phone-outline"
v-model="mobile"
clearable
@blur="check_mobile">
</el-input>
<el-input
placeholder="密码"
prefix-icon="el-icon-key"
v-model="password"
clearable
show-password>
</el-input>
<el-input
placeholder="验证码"
prefix-icon="el-icon-chat-line-round"
v-model="sms"
clearable>
<template slot="append">
<span class="sms" @click="send_sms">{{ sms_interval }}</span>
</template>
</el-input>
<el-button type="primary" @click="go_register">注册</el-button>
</el-form>
<div class="foot">
<span @click="go_login">立即登录</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Register",
data() {
return {
mobile: '',
password: '',
sms: '',
sms_interval: '获取验证码',
is_send: false,
}
},
methods: {
close_register() {
this.$emit('close', false)
},
go_login() {
this.$emit('go')
},
check_mobile() {
if (!this.mobile) return;
if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
this.$message({
message: '手机号有误',
type: 'warning',
duration: 1000,
onClose: () => {
this.mobile = '';
}
});
return false;
}
this.$axios.get(this.$settings.base_url + '/user/check_mobile/?mobile=' + this.mobile).then(res => {
if (res.data.status == 1) {
this.$message({
message: '手机号可以正常注册',
type: 'warning',
duration: 1000,
});
this.is_send = true;
} else {
this.$message({
message: res.data.msg,
type: 'warning',
duration: 1000,
onClose: () => {
this.mobile = '';
}
});
}
})
},
send_sms() {
if (!this.is_send) return;
this.is_send = false;
let sms_interval_time = 60;
this.sms_interval = "发送中...";
let timer = setInterval(() => {
if (sms_interval_time <= 1) {
clearInterval(timer);
this.sms_interval = "获取验证码";
this.is_send = true;
} else {
sms_interval_time -= 1;
this.sms_interval = `${sms_interval_time}秒后再发`;
}
}, 1000);
this.$axios.get(this.$settings.base_url + '/user/send_code/?mobile=' + this.mobile).then(res => {
this.$message({
message: res.data.msg,
type: 'info',
duration: 1000,
});
})
},
go_register() {
this.$axios.post(this.$settings.base_url + '/user/register/', {
'mobile': this.mobile,
'code': this.sms,
'password': this.password
}).then(res => {
this.$message({
message: res.data.msg,
type: 'info',
duration: 1000,
});
if (res.data.status == 0) {
this.go_login()
}
})
},
}
}
</script>
<style scoped>
.register {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 10;
background-color: rgba(0, 0, 0, 0.3);
}
.box {
width: 400px;
height: 480px;
background-color: white;
border-radius: 10px;
position: relative;
top: calc(50vh - 240px);
left: calc(50vw - 200px);
}
.el-icon-close {
position: absolute;
font-weight: bold;
font-size: 20px;
top: 10px;
right: 10px;
cursor: pointer;
}
.el-icon-close:hover {
color: darkred;
}
.content {
position: absolute;
top: 40px;
width: 280px;
left: 60px;
}
.nav {
font-size: 20px;
height: 38px;
border-bottom: 2px solid darkgrey;
}
.nav > span {
margin-left: 90px;
color: darkgrey;
user-select: none;
cursor: pointer;
padding-bottom: 10px;
border-bottom: 2px solid darkgrey;
}
.nav > span.active {
color: black;
border-bottom: 3px solid black;
padding-bottom: 9px;
}
.el-input, .el-button {
margin-top: 40px;
}
.el-button {
width: 100%;
font-size: 18px;
}
.foot > span {
float: right;
margin-top: 20px;
color: orange;
cursor: pointer;
}
.sms {
color: orange;
cursor: pointer;
display: inline-block;
width: 70px;
text-align: center;
user-select: none;
}
</style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)