文章目录
1、集成腾讯云短信服务
1.1、说明
1、API文档,接口的使用说明
2、SDK,基于开发语言封装的可以直接调用的功能(工具)集合
官网sdk使用文档中找到安装命令: pip install qcloudsms_py
按照sdk使用说明进行开发: https://cloud.tencent.com/document/product/382/11672
# 所有配置换成申请的数据
# 申请的短信应用 SDK AppID
appid = 1400
# 申请的短信应用 SDK AppKey
appkey = "ba81"
# 申请的短信模板ID,需要在短信控制台中申请
template_id = 5447
# 申请的签名,参数使用的是'签名内容',而不是'签名ID'
sms_sign = "allen的技术栈"
from qcloudsms_py import SmsSingleSender
sender = SmsSingleSender(appid, appkey)
import random
def get_code():
code = ''
for i in range(4):
code += str(random.randint(0, 9))
return code
mobile = 13344556677
# 模板所需参数和申请的模板中占位符要保持一致
code = get_code()
print(code)
params = [code, 5]
try:
result = sender.send_with_param(86, mobile, template_id, params, sign=sms_sign, extend="", ext="")
if result and result.get('result') == 0:
print('发送成功')
except Exception as e:
print('短信发送失败: %s' % e)
1.2、短信服务二次封装
在libs下创建 tx_sms 包
1.2.1、init.py
from .sms import get_code, send_code
1.2.2、settings.py
# 申请的短信应用 SDK AppID
APP_ID = 1400
# 申请的短信应用 SDK AppKey
APP_KEY = "ba81"
# 申请的短信模板ID,需要在短信控制台中申请
TEMPLATE_ID = 5447
# 申请的签名,参数使用的是'签名内容',而不是'签名ID'
SIGN = "allen的技术栈"
1.2.3、sms.py
import random
def get_code():
code = ''
for i in range(4):
code += str(random.randint(0, 9))
return code
from qcloudsms_py import SmsSingleSender
from . import settings
from utils.logging import logger
sender = SmsSingleSender(settings.APP_ID, settings.APP_KEY)
def send_code(mobile, code, exp):
try:
result = sender.send_with_param(
86,
mobile,
settings.TEMPLATE_ID,
(code, exp),
sign=settings.SIGN,
extend="", ext=""
)
if result and result.get('result') == 0:
return True
logger.error('短信发送失败: %s' % result.get('errmsg'))
except Exception as e:
logger.critical('短信发送异常: %s' % e)
return False
2、短信验证码接口
1、前端发送get请求,携带手机号,调用封装好的发送短信接口,完成发送短信,给用户返回提示信息
2 路由: send_code 视图函数: SendCodeView
3、恶意使用你的接口解决方式:
(1) 限制频: 手机号一分钟一次
(2) 限制ip: 一分钟一次
(3) 发送验证码之前,先输入验证码(可以集成极验滑动验证码)
2.1、路由
router.register('', views.SendCodeView, basename='sendcodeview')
2.2、视图函数
import re
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 mobile is None:
return APIResponse(status=1, msg='手机号不能为空')
if re.match(r'^1[3-9][0-9]{9}$', mobile):
# 生成验证码
code = sms.get_code()
flag, msg = sms.send_sms(mobile, code)
if flag:
# 保存验证码 3分钟
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='手机号不合法')
dev.py中缓存的配置
# 缓存到内存中
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # 指定缓存使用的引擎
'LOCATION': 'unique-snowflake', # 写在内存中的变量的唯一值
'TIMEOUT': 300, # 缓存超时时间(默认为300秒,None表示永不过期)
'OPTIONS': {
'MAX_ENTRIES': 300, # 最大缓存记录的数量(默认300)
'CULL_FREQUENCY': 3, # 缓存到达最大个数之后,剔除缓存个数的比例,即: 1/CULL_FREQUENCY(默认3)
}
}
}
user_setting.py中缓存的配置
SMS_CACHE_KEY = 'sms_cache_%(mobile)s'
SMS_CACHE_TIME = 60 * 3
3、短信登录接口
1、手机号+验证码 ---> post请求
2、手机号, code:
拿着手机号去用户表比较, 如果该手机号存在, 是我的注册用户
去缓存中取验证码 ---> 手机号在用户表中, 并且code是正确的, 登录成功, 签发token
3、更便捷登录: 使用本手机一键登录, 一键注册
4、路由: code_login ---> post请求 ---> {mobile:xxxx, code:1234}
127.0.0.0:8000/user/code_login/ ---> post
3.1、路由
router.register('', views.UserLoginView, basename='userloginview')
3.2、视图函数
class UserLoginView(ViewSet):
@action(methods=['POST', ], detail=False)
def code_login(self, request, *args, **kwargs):
ser = s.LoginCodeSerialzer(data=request.data, context={
'request': request,
})
if ser.is_valid():
user = ser.context['user']
token = ser.context['token']
icon = ser.context['icon']
return APIResponse(id=user.id, user=user.username, token=token, icon=icon)
else:
return APIResponse(status=1, msg=ser.errors)
3.3、序列化器
import re
from rest_framework import serializers
from rest_framework import exceptions
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from django.conf import settings
from django.core.cache import cache
from .models import User
class LoginCodeSerialzer(serializers.ModelSerializer):
mobile = serializers.CharField()
code = serializers.CharField()
class Meta:
model = User
fields = ('mobile', 'password', 'icon', 'code')
def validate_mobile(self, attrs):
if not re.match(r'^1[3-9][0-9]{9}$', attrs):
raise exceptions.ValidationError('mobile field error')
return attrs
def _check_code(self, attrs):
code_cache = cache.get(settings.SMS_CACHE_KEY % {'mobile': attrs.get('mobile')})
if code_cache == attrs.get('code') or attrs.get('code') == '8888':
return attrs.get('mobile')
else:
raise exceptions.ValidationError('验证码错误或过期')
def _get_user(self, mobile):
user = 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
4、短信注册接口
1、手机号+验证码 ---> 完成注册
2、路由: user/register ---> post请求 ---> {mobile: xxx,code:1234,password:111}
4.1、路由
router.register('register', views.CodeRegisterView, basename='coderegisterview')
4.2、视图函数
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
class CodeRegisterView(GenericViewSet, CreateModelMixin):
queryset = User.objects.all()
serializer_class = s.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.3、序列化器
class CodeRegisterSerializer(serializers.ModelSerializer):
code = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'mobile', 'password', 'code')
extra_kwargs = {
'username': {'read_only': True},
'password': {'write_only': True},
}
def validate(self, attrs):
if re.match(r'^1[3-9][0-9]{9}$', attrs.get('mobile')):
code_cache = cache.get(settings.SMS_CACHE_KEY % {'mobile': attrs.get('mobile')})
if code_cache == attrs.get('code') or attrs.get('code') == '8888':
# 删除验证码
attrs.pop('code')
return attrs
else:
raise exceptions.ValidationError('验证码不合法')
else:
raise exceptions.ValidationError('手机号不合法')
def create(self, validated_data):
validated_data['username'] = validated_data.get('mobile')
user = User.objects.create_user(**validated_data)
return user
5、前台登录注册功能(基于手机短信验证码)
5.1、注册
<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: true,
}
},
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: 'info',
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,
onClose: () => {
this.mobile = '';
}
});
})
},
go_register() {
this.$axios.post(this.$settings.base_url + '/user/register/', {
'mobile': this.mobile,
'password': this.password,
'code': this.sms,
}).then(res => {
this.$message({
message: res.data.msg,
type: 'info',
duration: 1000,
onClose: () => {
this.mobile = '';
}
});
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>
5.2、登录
<template>
<div class="login">
<div class="box">
<i class="el-icon-close" @click="close_login"></i>
<div class="content">
<div class="nav">
<span :class="{active: login_method === 'is_pwd'}"
@click="change_login_method('is_pwd')">密码登录</span>
<span :class="{active: login_method === 'is_sms'}"
@click="change_login_method('is_sms')">短信登录</span>
</div>
<el-form v-if="login_method === 'is_pwd'">
<el-input
placeholder="用户名/手机号/邮箱"
prefix-icon="el-icon-user"
v-model="username"
clearable>
</el-input>
<el-input
placeholder="密码"
prefix-icon="el-icon-key"
v-model="password"
clearable
show-password>
</el-input>
<el-button type="primary" @click="login_pwd">登录</el-button>
</el-form>
<el-form v-if="login_method === 'is_sms'">
<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-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_login">登录</el-button>
</el-form>
<div class="foot">
<span @click="go_register">立即注册</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Login",
data() {
return {
username: '',
password: '',
mobile: '',
sms: '',
login_method: 'is_pwd',
sms_interval: '获取验证码',
is_send: false,
}
},
methods: {
close_login() {
this.$emit('close')
},
go_register() {
this.$emit('go')
},
change_login_method(method) {
this.login_method = method;
},
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.is_send = true;
},
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);
},
login_pwd() {
this.$axios.post(this.$settings.base_url + '/user/login/', {
username: this.username,
password: this.password,
}).then(item => {
// console.log(item)
if (item.data.status == 0) {
this.$cookies.set('username', item.data.username, '7d');
this.$cookies.set('token', item.data.token, '7d');
this.$cookies.set('icon', item.data.icon, '7d');
this.$cookies.set('id', item.data.id, '7d');
// 关闭模态框
this.close_login()
} else {
this.$message({
message: '用户名或密码有误',
type: 'error',
duration: 1000,
onClose: () => {
this.username = '';
this.password = '';
}
});
}
})
},
go_login() {
this.$axios.post(this.$settings.base_url + '/user/code_login/', {
'code': this.sms,
'mobile': this.mobile,
'password': this.password,
}).then(item => {
if (item.data.status == 0) {
this.$cookies.set('username', item.data.user, '7d');
this.$cookies.set('token', item.data.token, '7d');
this.$cookies.set('icon', item.data.icon, '7d');
this.$cookies.set('id', item.data.id, '7d');
// 关闭模态框
this.close_login()
} else {
this.$message({
message: '用户名或密码有误',
type: 'error',
duration: 1000,
onClose: () => {
this.username = '';
this.password = '';
}
});
}
})
},
}
}
</script>
<style scoped>
.login {
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: 420px;
background-color: white;
border-radius: 10px;
position: relative;
top: calc(50vh - 210px);
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: 0 20px 0 35px;
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>