异步发送短信
1.原来的发送短信,是同步
前端输入手机号--->点击发送短信--->前端发送ajax请求--->到咱们后端接口--->取出手机号---->调用腾讯发送短信--->腾讯去发短信--->发完后---->回复给我们后端发送成功--->我们后端收到发送成功--->给我们前端返回发送成功
2.把腾讯发送短信的过程,变成异步
前端输入手机号--->点击发送短信--->前端发送ajax请求---->到咱们后端接口--->取出手机号---->开启线程,去调用腾讯短信发送(异步)--->我们后端继续往后走---->直接返回给前端,告诉前端短信已发送
另一条发短信线程线程会去发送短信,至于是否成功,我们不管了
视图类
from rest_framework.viewsets import ViewSet,GenericViewSet
from rest_framework.decorators import action
from .models import User
from rest_framework.exceptions import APIException
from utils.common_logger import logger
from .serializer import MulLoginSerializer,SmsLoginSerializer,RegisterSerializer
from libs.send_tx_sms import get_code,send_sms_by_mobile
from django.core.cache import cache
from threading import Thread
class UserView(GenericViewSet):
serializer_class = MulLoginSerializer
@action(methods=['GET'], detail=False)
def check_mobile(self, request, *args, **kwargs):
...
@action(methods=['GET'], detail=False)
def send_sms(self,request, *args, **kwargs):
# 前端需要把要发送的手机号传入 在地址栏中
mobile = request.query_params.get('mobile',None)
# print(mobile)
code =get_code() # 把code存起来,放到缓存中
print(code)
cache.set('send_sms_code_%s'%mobile,code)
# 从缓存中取
# cache.get('send_sms_code_%s'%mobile)
if mobile:
# 开启线程
t=Thread(target=send_sms_by_mobile,args=(mobile,code))
t.start()
# send_sms_by_mobile(mobile,code)
return APIResponse(msg='短信已经发送了')
raise APIException('没有手机号')
def get_serializer_class(self):
...
@action(methods=['POST'], detail=False)
def sms_login(self,request, *args, **kwargs):
...
def _common_login(self,request, *args, **kwargs):
...
ps:可以在send_sms_by_mobile函数中,导入time模块,等待几秒,查看效果
序列化类加入万能验证吗
class SmsLoginSerializer(CommonLoginSerializer,serializers.Serializer):
mobile = serializers.CharField(required=True)
code = serializers.CharField(required=True)
def _get_user(self, attrs):
mobile = attrs.get('mobile')
code = attrs.get('code')
# 比对验证码
old_code=cache.get('send_sms_code_%s' % mobile)
# 如果是 debug模式,有个万能验证码,这样就不用真正发送短信了
if old_code ==code or (settings.DEBUG and code=='8888'):
# 验证码正确,获取user
user=User.objects.filter(mobile=mobile).first()
if user:
return user
else:
raise APIException('手机号没注册')
else:
raise APIException('验证码错误')
注册功能
1.前端传入的数据
{"mobile":xxxx,"code":xxx,"password":xxx}
2.后端要验证数据--->序列化类
3.可能遇到的错误(注意事项)
1.注册使用哪个序列化了:get_serializer_class
2.配置文件中debug必须是True,因为我们有万能验证码--->正常流程这个不需要
3.在全局钩子中,把code,弹出来,加入用户名,你可以随机生成用户名
4.重写create(可以不重写,把密码设为加密的密码),create_user
5.如果你继承了CreateModelMixin,一定要注意,它会走序列化,所以code字段是只写的
方式一
视图类
from rest_framework.viewsets import ViewSet,GenericViewSet
from rest_framework.decorators import action
from .models import User
from rest_framework.exceptions import APIException
from utils.common_logger import logger
from .serializer import MulLoginSerializer,SmsLoginSerializer,RegisterSerializer
from libs.send_tx_sms import get_code,send_sms_by_mobile
from django.core.cache import cache
from threading import Thread
class UserView(GenericViewSet):
serializer_class = MulLoginSerializer
@action(methods=['GET'], detail=False)
def check_mobile(self, request, *args, **kwargs):
...
@action(methods=['POST'], detail=False)
def mul_login(self, request, *args, **kwargs):
...
@action(methods=['GET'], detail=False)
def send_sms(self,request, *args, **kwargs):
...
def get_serializer_class(self):
if self.action=='sms_login':
return SmsLoginSerializer
elif self.action =='register':
return RegisterSerializer
else:
# return super().get_serializer_class()
return self.serializer_class
@action(methods=['POST'], detail=False)
def sms_login(self,request, *args, **kwargs):
...
def _common_login(self,request, *args, **kwargs):
...
@action(methods=['POST'],detail=False)
def register(self,request, *args, **kwargs):
ser = self.get_serializer(data=request.data)
ser.is_valid(raise_exception=True)
ser.save()
return APIResponse(msg='注册成功')
序列化类
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields=['mobile','password','code']
code = serializers.CharField(max_length=4,min_length=4)
# 反序列化,走自己的字段,局部钩子,全局钩子
# 局部钩子,手机号校验
def validate_mobile(self,mobile):
res = re.findall('^1([3578][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$',mobile)
if not res:
raise APIException('手机号不合法')
else:
return mobile
def _check_code(self,attrs):
code = attrs.get('code')
mobile = attrs.get('mobile')
old_code = cache.get('send_sms_code_%s' % mobile)
if not(old_code == code or (settings.DEBUG and code == '8888')):
raise APIException('验证码不对哦')
def _pre_create(self,attrs):
attrs.pop('code')
attrs['username']=attrs.get('mobile')
return attrs
# 全局钩子:{"mobile":xxxx,"code":xxx,"password":xxx}
def validate(self, attrs):
# 1.比对code
self._check_code(attrs)
# 2.保存前准备
self._pre_create(attrs)
return attrs
def create(self, validated_data): # {"mobile":xxxx,"username":xxx,"password":xxx}
user = User.objects.create_user(**validated_data)
return user
方式二
视图类
from rest_framework.viewsets import ViewSet,GenericViewSet
from rest_framework.decorators import action
from .models import User
from rest_framework.exceptions import APIException
from utils.common_logger import logger
from .serializer import MulLoginSerializer,SmsLoginSerializer,RegisterSerializer
from libs.send_tx_sms import get_code,send_sms_by_mobile
from django.core.cache import cache
from threading import Thread
from rest_framework.mixins import CreateModelMixin
class UserView(GenericViewSet,CreateModelMixin):
serializer_class = MulLoginSerializer
@action(methods=['GET'], detail=False)
def check_mobile(self, request, *args, **kwargs):
...
@action(methods=['POST'], detail=False)
def mul_login(self, request, *args, **kwargs):
...
@action(methods=['GET'], detail=False)
def send_sms(self,request, *args, **kwargs):
...
def get_serializer_class(self):
if self.action=='sms_login':
return SmsLoginSerializer
elif self.action =='register' or self.action =='create':
return RegisterSerializer
else:
# return super().get_serializer_class()
return self.serializer_class
@action(methods=['POST'], detail=False)
def sms_login(self,request, *args, **kwargs):
...
def _common_login(self,request, *args, **kwargs):
...
序列化类
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields=['mobile','password','code']
code = serializers.CharField(max_length=4,min_length=4,write_only=True)
# 局部钩子,手机号校验
def validate_mobile(self,mobile):
...
def _check_code(self,attrs):
...
def _pre_create(self,attrs):
...
# 全局钩子:{"mobile":xxxx,"code":xxx,"password":xxx}
def validate(self, attrs):
...
def create(self, validated_data):
...
class CreateModelMixin:
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
ps:serializer.data-->序列化要调用它,只要调用serializer.data ,就会走序列化,只要走序列化,会把create返回的user对象 来使用UserRegisterSerializer类做序列化
改进返回格式,就不用修改code的字段(不用写write_only=True)
from rest_framework.viewsets import ViewSet,GenericViewSet
from rest_framework.decorators import action
from .models import User
from rest_framework.exceptions import APIException
from utils.common_logger import logger
from .serializer import MulLoginSerializer,SmsLoginSerializer,RegisterSerializer
from libs.send_tx_sms import get_code,send_sms_by_mobile
from django.core.cache import cache
from threading import Thread
from rest_framework.mixins import CreateModelMixin
class UserView(GenericViewSet,CreateModelMixin):
serializer_class = MulLoginSerializer
@action(methods=['GET'], detail=False)
def check_mobile(self, request, *args, **kwargs):
...
@action(methods=['POST'], detail=False)
def mul_login(self, request, *args, **kwargs):
...
@action(methods=['GET'], detail=False)
def send_sms(self,request, *args, **kwargs):
...
def get_serializer_class(self):
if self.action=='sms_login':
return SmsLoginSerializer
elif self.action =='register' or self.action =='create':
return RegisterSerializer
else:
# return super().get_serializer_class()
return self.serializer_class
@action(methods=['POST'], detail=False)
def sms_login(self,request, *args, **kwargs):
...
def _common_login(self,request, *args, **kwargs):
...
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return APIResponse(msg='注册成功') # #不走序列化了,序列类中得write_only 也就不用了
补充
1.为什么要写这个media才能访问
-django 默认是不允许前端直接访问项目某个文件夹的
-有个static文件夹例外,需要额外配置
-如果想让用户访问,必须配置路由,使用serve函数放开
path('media/<path:path>', serve, {'document_root': settings.MEDIA_ROOT})
-浏览器中访问 meida/icon/1.png--->能把settings.MEDIA_ROOT对应的文件夹下的icon/1.png返回给前端
path('lqz/<path:path>', serve, {'document_root':os.path.join(BASE_DIR, 'lqz')})
浏览器中访问 lqz/a.txt----->能把项目根路径下lqz对应的文件夹下的a.txt返回给前端
2.配置文件中 debug作用
-开发阶段,都是debug为True,信息显示更丰富
你访问的路由如果不存在,会把所有能访问到的路由都显示出来
程序出了异常,错误信息直接显示在浏览器上
自动重启,只要改了代码,会自动重启
-上线阶段,肯定要改成False
3.ALLOWED_HOSTS 的作用
-只有debug 为Flase时,这个必须填
-限制后端项目(django项目 )能够部署在哪个ip的机器上,写个 * 表示所有地址都可以
4.咱们的项目中,为了知道是在调试模式还是在上线模式,所以才用的debug这个字段
-判断,如果是开发阶段,可以有个万能验证码
5.短信登录或注册接口优化
-app 只需要输入手机号和验证码,如果账号不存在,直接注册成功,并且登录成功,如果账号存在,就是登录
-前端传入:{mobiel,code}--->验证验证码是否正确--->拿着mobile去数据库查询,如果能查到,说明它注册过了,直接签发token返回---->如果查不到,没有注册过---》走注册逻辑完成注册---》再签发token,返回给前端
-这个接口,随机生成一个6位密码,以短信形式通知用户
-这个接口,密码为空,下次他用账号密码登录,不允许登录
前端注册页面分析
1.登录,注册,都写成组件---->在任意页面中,都能点击显示登录模态框
2.写好的组件,应该放在那个组件中---->不是页面组件(小组件)
3.点击登录按钮,把Login.vue 通过定位,占满全屏,透明度设为 0.5 ,纯黑色悲剧,覆盖在组件上
4.在Login.vue点关闭,要把Login.vue隐藏起来,父子通信之子传父,自定义事件
模态框简单演示
Login
<template>
<div class="login">
<div @click="myclick11">x</div>
</div>
</template>
<script>
export default {
name: "Login",
methods:{
myclick11(){
this.$emit('myclick')
}
}
}
</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);
}
</style>
Header.vue
<template>
<div class="header">
<Login @myclick="handelout" v-if="is_show"></Login>
<Register></Register>
</div>
</div>
</template>
<script>
import Login from '@/components/Login.vue'
import Register from "@/components/Register.vue";
export default {
name: "Header",
data() {
return {
is_show:true
}
},
methods: {
handelout(){
this.is_show=false
}
},
components:{
Login,Register
}
}
</script>
前端登陆页面复制
Login.vue
<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">登录</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">登录</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);
}
}
}
</script>
<style scoped>
.login {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 10;
background-color: rgba(0, 0, 0, 0.5);
}
.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>
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">注册</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.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);
}
}
}
</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>
Header.vue
<template>
<div class="header">
<div class="right-part">
<div>
<span @click="put_login">登录</span>
<span class="line">|</span>
<span @click="put_register">注册</span>
</div>
</div>
<Login v-if="is_login" @close="close_login" @go="put_register"></Login>
<Register v-if="is_register" @close="close_register" @go="put_login"></Register>
</div>
</div>
</template>
<script>
import Login from '@/components/Login.vue'
import Register from "@/components/Register.vue";
import th from "element-ui/src/locale/lang/th";
export default {
name: "Header",
data() {
return {
is_login:false,
is_register:false
}
},
methods: {
close_login(){
this.is_login=false
},
close_register(){
this.is_register=false
},
put_register(){
this.is_login=false
this.is_register=true
},
put_login(){
this.is_register=false
this.is_login=true
}
},
created() {
},
components:{
Login,Register
}
}
</script>
<style scoped>
</style>
前端登陆功能
1.多方式登录的axios请求,保存cookie--->Header.vue中要写created 生命周期,取出当前登录用户-->close_login取出当前登录用户
2.手机号验证码登录,axios请求,保存cookie
3.发送短信验证码
Login
<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="handleLogin">登录</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="SmsLogin">登录</el-button>
</el-form>
<div class="foot">
<span @click="go_register">立即注册</span>
</div>
</div>
</div>
</div>
</template>
<script>
import el from "element-ui/src/locale/lang/el";
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.$axios.get(`${this.$settings.BASE_URL}user/userinfo/check_mobile/?mobile=${this.mobile}`).then(res => {
if (res.data.code == 100) {
this.is_send = true;
} else {
this.$message({
message: res.data.error_msg,
type: 'warning'
})
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/userinfo/send_sms/?mobile=${this.mobile}`).then(res => {
if (res.data.code == 100) {
this.$message({
message: res.data.msg,
type: 'success'
})
} else {
this.$message({
message: res.data.error_msg,
type: 'warning'
})
}
})
},
handleLogin() {
this.$axios.post(`${this.$settings.BASE_URL}user/userinfo/mul_login/`, {
username: this.username,
password: this.password
}).then(res => {
if (res.data.code == 100) {
//登陆成功,将返回的icon、token、username保存在cookie中
this.$cookies.set("username", res.data.user, '7d')
this.$cookies.set("icon", res.data.icon, '7d')
this.$cookies.set("token", res.data.token, '7d')
this.$emit('close')
} else {
//弹窗
this.$message({
message: res.data.error_msg,
type: 'warning'
})
}
})
},
SmsLogin() {
this.$axios.post(`${this.$settings.BASE_URL}user/userinfo/sms_login/`, {
mobile: this.mobile,
code: this.sms
}).then(res => {
if (res.data.code == 100) {
this.$cookies.set("username", res.data.user, '7d')
this.$cookies.set("icon", res.data.icon, '7d')
this.$cookies.set("token", res.data.token, '7d')
this.$emit('close')
} else {
this.$message({
message: res.data.error_msg,
type: 'warning'
})
}
})
}
}
}
</script>
<style scoped>
.login {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 10;
background-color: rgba(0, 0, 0, 0.5);
}
.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>
Header.vue
<template>
<div class="header">
<div class="slogan">
<p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
</div>
<div class="nav">
<ul class="left-part">
<li class="logo">
<router-link to="/">
<img src="../assets/img/head-logo.svg" alt="">
</router-link>
</li>
<li class="ele">
<span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
</li>
<li class="ele">
<span @click="goPage('/actual-course')"
:class="{active: url_path === '/actual-course'}">实战课</span>
</li>
<li class="ele">
<span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
</li>
</ul>
<div class="right-part">
<div v-if="username">
<span >{{username}}</span>
<span class="line">|</span>
<span @click="LoginOut">注销</span>
</div>
<div v-else>
<span @click="put_login">登录</span>
<span class="line">|</span>
<span @click="put_register">注册</span>
</div>
</div>
<Login v-if="is_login" @close="close_login" @go="put_register"></Login>
<Register v-if="is_register" @close="close_register" @go="put_login"></Register>
</div>
</div>
</template>
<script>
import Login from '@/components/Login.vue'
import Register from "@/components/Register.vue";
import th from "element-ui/src/locale/lang/th";
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
is_login: false,
is_register: false,
username:''
}
},
methods: {
goPage(url_path) {
// 已经是当前路由就没有必要重新跳转
if (this.url_path !== url_path) {
this.$router.push(url_path);
}
sessionStorage.url_path = url_path;
},
close_login() {
this.is_login = false
this.username = this.$cookies.get('username')
},
close_register() {
this.is_register = false
},
put_register() {
this.is_login = false
this.is_register = true
},
put_login() {
this.is_register = false
this.is_login = true
},
LoginOut(){
this.$cookies.remove('icon')
this.$cookies.remove('username')
this.$cookies.remove('token')
this.username=''
}
},
created() {
sessionStorage.url_path = this.$route.path;
this.url_path = this.$route.path;
//如果有username,就显示:用户名和注销;如果没有username,就显示:登陆和注册
this.username=this.$cookies.get('username')
},
components: {
Login, Register
}
}
</script>
<style scoped>
.header {
background-color: white;
box-shadow: 0 0 5px 0 #aaa;
}
.header:after {
content: "";
display: block;
clear: both;
}
.slogan {
background-color: #eee;
height: 40px;
}
.slogan p {
width: 1200px;
margin: 0 auto;
color: #aaa;
font-size: 13px;
line-height: 40px;
}
.nav {
background-color: white;
user-select: none;
width: 1200px;
margin: 0 auto;
}
.nav ul {
padding: 15px 0;
float: left;
}
.nav ul:after {
clear: both;
content: '';
display: block;
}
.nav ul li {
float: left;
}
.logo {
margin-right: 20px;
}
.ele {
margin: 0 20px;
}
.ele span {
display: block;
font: 15px/36px '微软雅黑';
border-bottom: 2px solid transparent;
cursor: pointer;
}
.ele span:hover {
border-bottom-color: orange;
}
.ele span.active {
color: orange;
border-bottom-color: orange;
}
.right-part {
float: right;
}
.right-part .line {
margin: 0 10px;
}
.right-part span {
line-height: 68px;
cursor: pointer;
}
</style>
前端注册功能
1.校验手机号是否存在的axios
如果存在,直接跳转到登录--->小bug
2.发送验证码axios
3.注册的axios
-注册成功,跳转到登录页面
Register
<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="HandleRegister">注册</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/userinfo/check_mobile/?mobile=${this.mobile}`).then(res => {
if (res.data.code != 100) {
this.is_send = true;
} else {
this.$message({
message: '电话已经存在',
type: 'warning'
})
this.mobile = ''
}
})
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);
//发送短信
this.$axios.get(`${this.$settings.BASE_URL}user/userinfo/send_sms/?mobile=${this.mobile}`).then(res=>{
if (res.data.code==100){
this.$message({
message: res.data.msg,
type: 'success'
})
}else{
this.$message({
message: res.data.error_msg,
type: 'warning'
})
}
})
},
HandleRegister(){
this.$axios.post(`${this.$settings.BASE_URL}user/userinfo/register/`,{
mobile:this.mobile,
password:this.password,
code:this.sms
}).then(res=>{
if (!res.data.code==100){
this.$message({
message: res.data.error_msg,
type: 'warning'
})
}else{
this.$emit('go')
}
})
}
}
}
</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>
Header.vue
<template>
<div class="header">
<div class="slogan">
<p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
</div>
<div class="nav">
<ul class="left-part">
<li class="logo">
<router-link to="/">
<img src="../assets/img/head-logo.svg" alt="">
</router-link>
</li>
<li class="ele">
<span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
</li>
<li class="ele">
<span @click="goPage('/actual-course')"
:class="{active: url_path === '/actual-course'}">实战课</span>
</li>
<li class="ele">
<span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
</li>
</ul>
<div class="right-part">
<div v-if="username">
<span >{{username}}</span>
<span class="line">|</span>
<span @click="LoginOut">注销</span>
</div>
<div v-else>
<span @click="put_login">登录</span>
<span class="line">|</span>
<span @click="put_register">注册</span>
</div>
</div>
<Login v-if="is_login" @close="close_login" @go="put_register"></Login>
<Register v-if="is_register" @close="close_register" @go="put_login"></Register>
</div>
</div>
</template>
<script>
import Login from '@/components/Login.vue'
import Register from "@/components/Register.vue";
import th from "element-ui/src/locale/lang/th";
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
is_login: false,
is_register: false,
username:''
}
},
methods: {
goPage(url_path) {
// 已经是当前路由就没有必要重新跳转
if (this.url_path !== url_path) {
this.$router.push(url_path);
}
sessionStorage.url_path = url_path;
},
close_login() {
this.is_login = false
this.username = this.$cookies.get('username')
},
close_register() {
this.is_register = false
},
put_register() {
this.is_login = false
this.is_register = true
},
put_login() {
this.is_register = false
this.is_login = true
},
LoginOut(){
this.$cookies.remove('icon')
this.$cookies.remove('username')
this.$cookies.remove('token')
this.username=''
}
},
created() {
sessionStorage.url_path = this.$route.path;
this.url_path = this.$route.path;
//如果有username,就显示:用户名和注销;如果没有username,就显示:登陆和注册
this.username=this.$cookies.get('username')
},
components: {
Login, Register
}
}
</script>
<style scoped>
.header {
background-color: white;
box-shadow: 0 0 5px 0 #aaa;
}
.header:after {
content: "";
display: block;
clear: both;
}
.slogan {
background-color: #eee;
height: 40px;
}
.slogan p {
width: 1200px;
margin: 0 auto;
color: #aaa;
font-size: 13px;
line-height: 40px;
}
.nav {
background-color: white;
user-select: none;
width: 1200px;
margin: 0 auto;
}
.nav ul {
padding: 15px 0;
float: left;
}
.nav ul:after {
clear: both;
content: '';
display: block;
}
.nav ul li {
float: left;
}
.logo {
margin-right: 20px;
}
.ele {
margin: 0 20px;
}
.ele span {
display: block;
font: 15px/36px '微软雅黑';
border-bottom: 2px solid transparent;
cursor: pointer;
}
.ele span:hover {
border-bottom-color: orange;
}
.ele span.active {
color: orange;
border-bottom-color: orange;
}
.right-part {
float: right;
}
.right-part .line {
margin: 0 10px;
}
.right-part span {
line-height: 68px;
cursor: pointer;
}
</style>
补充
serizlier_class、get_serializer_class、get_serializer区别
1.serizlier_class:类属性,必须继承GenericAPIView,才能配置再类中,指定序列化类
2.get_serializer_class:方法,GenericAPIView类中的方法,作用返回序列化类,默认返回serizlier_class,【它的重点是可以重写,定制我们需要返回的序列化类,视图类中可能有很多方法,不同方法用的序列化类不一样,就可以通过它定制】
3.get_serializer:方法,GenericAPIView类中的方法,作用是把传入的数据,做成序列化类的对象,根据get_serializer_class返回不同,序列化类对象不同
作业
1.参考文档:https://gitee.com/liuqingzheng/rbac_manager/tree/master/libs/lqz_jwt,研究配置文件的编写
2.写个短信登录注册接口(只需要传手机号和验证码,生成一个默认密码,以短信形式通知用户)
3.登录接口,如果是用默认密码,不允许登录
4.记录三次用户密码修改记录,每次改密码,不能跟之前用过的相同
5.https://blog.csdn.net/weixin_46407419/article/details/124855081