0. 删除默认的导航条
删除后
1. 登入模态框组件(伪代码)
看模态框的效果
1.1 组件代码
在src下的components目录下创建一个模态框子组件.
<template>
<div class="login">
<span @click="close_modal">X</span>
</div>
</template>
<script>
export default {
name: "LoginModal",
methods: {
close_modal() {
this.$emit('close')
}
}
}
</script>
<style scoped>
.login {
width: 100vw;
height: 100vw;
position: fixed;
left: 0;
top: 0;
z-index: 666;
background-color: rgba(0, 255, 0, 0.3);
}
span {
font-size: 30px;
cursor: pointer;
}
</style>
1.2 使用组件(省略代码)
在Head.vue中导入模态框子组件, 点击登入触发模态框.
<template>
<div class="header">
<span @click="open_modal">登录</span>
<LoginModal v-if="is_show" @close="close_modal"></LoginModal>
</div>
</template>
<script>
import LoginModal from './LoginModal'
export default {
name: "Header",
data() {
return {
is_show: false,
}
},
components: {
LoginModal,
},
methods: {
open_modal() {
this.is_show = true
},
close_modal(){
this.is_show = false
}
},
}
</script>
1.3 使用组件(完整代码)
<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>
<span @click="open_modal">登录</span>
<span class="line">|</span>
<span>注册</span>
</div>
</div>
<LoginModal v-if="is_show" @close="close_modal"></LoginModal>
</div>
</div>
</template>
<script>
import LoginModal from './LoginModal'
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
is_show: false,
}
},
components: {
LoginModal,
},
methods: {
goPage(url_path) {
if (this.url_path !== url_path) {
this.$router.push(url_path);
}
sessionStorage.url_path = url_path;
},
open_modal() {
this.is_show = true
},
close_modal(){
this.is_show = false
}
},
created() {
sessionStorage.url_path = this.$route.path;
this.url_path = this.$route.path;
}
}
</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.4 效果展示
2. 登入/注册模态框
2.1 登入模态框组件
在src下的components目录下LoginModal.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.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>
2.2 注册模态框组件
在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">注册</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>
2.3 使用登入注册组件
<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>
<span @click="put_login">登录</span>
<span class="line">|</span>
<span @click="put_register">注册</span>
<span>注册</span>
</div>
</div>
<LoginModal v-if="is_login" @close="close_login" @go="put_register"/>
<Register v-if="is_register" @close="close_register" @go="put_login"/>
</div>
</div>
</template>
<script>
import LoginModal from './LoginModal'
import Register from './Register'
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
is_login: false,
is_register: false,
}
},
methods: {
goPage(url_path) {
if (this.url_path !== url_path) {
this.$router.push(url_path);
}
sessionStorage.url_path = url_path;
},
put_login() {
this.is_login = true;
this.is_register = false;
},
put_register() {
this.is_login = false;
this.is_register = true;
},
close_login() {
this.is_login = false;
},
close_register() {
this.is_register = false;
}
},
created() {
sessionStorage.url_path = this.$route.path;
this.url_path = this.$route.path;
},
components: {
LoginModal,
Register
}
}
</script>
2.4 效果展示
3. 多方式登入-密码登入
账户名/手机号/邮箱
需要校验的字段:
用户名(重新定义, 不走模型表的校验, 自定义校验规则)
用户密码(继承了内置用户表, 使用check_password加密在作密码对比)
需要返回:
id
用户名
token
手机号码手动输入
在注册账户的时候最好避免手机号就账户名, 一些网站检验输入的账户名, 必有有字母!
3.1 模型序列化器
在user apps中新建serializer.py 文件
from rest_framework import serializers
from user import models
class UserModelSerializer(serializers.ModelSerializer):
username = serializers.CharField()
class Meta:
model = models.User
fields = ['username', 'password', ]
extra_kwargs = {
'password': {'write_only': True},
}
def validate(self, attrs):
user_obj = self._get_user_obj(attrs)
token = self._get_token(user_obj)
self._context['token'] = token
self._context['username'] = user_obj.username
return attrs
@staticmethod
def _get_user_obj(attrs):
import re
from rest_framework.exceptions import ValidationError
username = attrs.get('username')
password = attrs.get('password')
if re.match('^1[3-9][0-9]{9}$', username):
user_obj = models.User.objects.filter(phone=username).first()
elif re.match('^.+@.+$', username):
user_obj = models.User.objects.filter(email=username).first()
else:
user_obj = models.User.objects.filter(username=username).first()
if not user_obj:
raise ValidationError('账户输入有误!')
if not user_obj.check_password(password):
raise ValidationError('密码输入有误!')
return user_obj
@staticmethod
def _get_token(user_obj):
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
payload = jwt_payload_handler(user_obj)
token = jwt_encode_handler(payload)
return token
在dev.py配置文件中配置token的过期时间(一般设置为7天)
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7)}
3.2 视图类
apps/user的视图层中编辑返回的信息
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from luffy.utils.api_response import ResponseDataFormat
from rest_framework.decorators import action
...
class LoginView(ViewSet):
@action(methods=['POST'], detail=False)
def login(self, request, *args, **kwargs):
from user.serializer import UserModelSerializer
ser = UserModelSerializer(data=request.data)
ser.is_valid(raise_exception=True)
token = ser.context['token']
username = ser.context['username']
return ResponseDataFormat(username=username, token=token)
3.3 路由层
项目名目录下的主路由
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
from xadmin.plugins import xversion
import xadmin
xversion.register_models()
xadmin.autodiscover()
urlpatterns = [
re_path('^xadmin/', xadmin.site.urls),
re_path('^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
path('home/', include('home.urls')),
path('user/', include('user.urls')),
]
apps/user下的子路由
视图类继承了ViewSet, 使用routers模块自动生成路由.
from django.urls import path, re_path, include
from user import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('', views.LoginView, 'login')
urlpatterns = [
re_path('exception_log/', views.ExceptionLog.as_view()),
path('', include(router.urls)),
]
router.register('', views.LoginView, 'login')
path('', include(router.urls)),
3.4 Postman中测试
* 1. 正常测试
访问地址: http://127.0.0.1:8000/user/login/
输入一个存在的账户(可以是 手机号/邮箱/用户名)
* 2. 错误测试
访问地址: http://127.0.0.1:8000/user/login/
输入一个不存在的账户
3.5 前端登入
* 1. 在登入模态框LoginModal.vue中绑定登入事件
<el-button type="primary" @click="password_login">登录</el-button>
* 2. 点击事件中使用axios发送post请求给后端
等入成功之后把用户名和token保存到cookies中
存:
this.$cookies.set('键', '值', '过期时间') 过期时间单位为秒, 开业使用'7d'表示七天.
取:
this.$cookies.get('键',)
移除:
this.$cookies.remove('键')
password_login() {
console.log(this.username && this.password)
if (this.username && this.password) {
this.$axios.post(this.$settings.base_url + '/user/login/', {
username: this.username, password: this.password
}).then(response => {
if (response.data.code === 200) {
this.$cookies.set('username', response.data.username)
this.$cookies.set('token', response.data.token)
this.$emit('close')
this.$emit('login_status')
}else{
this.$message({
message: response.data.data[0],
type: 'warning',
duration: 2000,
})
}
})
} else {
this.$message({
message: '你有信息没有填写',
type: 'warning',
duration: 2000,
})
}
},
* 3. 登入之后立刻修改登入状态
登入|注册 改为--> 用户名|注销
通过子传父将触发父组件, 父组件去cookies中获取用户名, 修改值之后动态刷新页面.
this.$emit('login_status')
在Head.vue组件中定义一个username变量, 通过判断username的是否有值切换右侧导航条的显示
username通过登入模态框子组件触发.
<div class="right-part">
<div v-if="!username">
<span @click="put_login">登录</span>
<span class="line">|</span>
<span @click="put_register">注册</span>
</div>
<div v-if="username">
<span>{{username}}</span>
<span class="line">|</span>
<span>注销</span>
</div>
</div>
<script>
data() {
return {
...
username: '',
token: '',
},
methods: {
...
loginStatus(){
this.username = this.$cookies.get('username')
this.token = this.$cookies.get('token')
}
}
</script>
* 4. 以后在打开页面, 先去cookies中获用户的信息, 如果有数据, 直接为登入状态.
在生命周期钩子函数中created中获取.
created() {
...
this.username = this.$cookies.get('username')
this.token = this.$cookies.get('token')
},
* 5. 注销登入
为注销绑定点击事件
将cookies中的用户数据清除, 再该变username变量的值, 自动刷新页面.
<span @click="logout">注销</span>
<script>
methods: {
logout() {
this.$cookies.remove('username')
this.$cookies.remove('token')
this.username = ''
this.token = ''
}
}
</script>
4. 多方式登入-手机号登入
4.1 判断手机号是否存在
* 1. 判断手机号是否在数据库中
class LoginView(ViewSet):
@action(methods=['GET'], detail=False)
def inquire_phone(self, request):
phone = request.query_params.get('phone')
is_exist = {'is_exist': False}
if not re.match('^1[3-9][0-9]{9}$', phone):
return ResponseDataFormat(code=400, msg='手机号码不合法!', data=is_exist)
user_obj = models.User.objects.filter(phone=phone).first()
if not user_obj:
return ResponseDataFormat(code=400, msg='手机号码没有注册!', data=is_exist)
is_exist = {'is_exist': True}
return ResponseDataFormat(data=is_exist)
* 2. Psetman中测试访问地址
http://127.0.0.1:8000/user/inquire_phone/?phone=18123456789
4.2 腾讯云短行服务
腾讯云短行服务地址: https://cloud.tencent.com/search/%E7%9F%AD%E4%BF%A1/1_1
1. 申请开通短信服务
* 1. 免费使用
* 2. 同意协议, 开始接入
2. 创建签名
* 1. 创建签名
* 2. 签名选择微信公众号(不需要营业执照)
* 3. 申请一个公众号, 复制公众号设置页面
* 4. 等待审核...
* 5. 复制签名内容: Python梦想空间
3. 创建短信模板
* 1. 创建短信模板
* 2. 等待审核...
* 3. 复制模板id: 1410883
4. 创建应用
* 1. 创建短信模板自动创建一个应用.
* 2. 应用列表中复制 SDK AppID 与 App Key
SDK AppID: 14006828197:
App Key: 87971852ee0862096105de36b05cb1d1d2d3
5. 帮助文档
帮助文档中有API的接口文档, 还提供了SDK的文档.
SDK: 软件开发工具包, 辅助开发某一类软件的相关文档.
SDK 2.0 地址: https://cloud.tencent.com/document/product/382/11672
4.3 示例代码
* 1. 安装qcloudsms_py模块
pip install qcloudsms_py
* 2. 示例代码
在script下新建test_send_mes.py
appid = 1400682819
appkey = "87971852ee0862096105de36b05cb1d1"
phone_numbers = ["自己的手机号码", ]
template_id = 1410883
sms_sign = "Python梦想空间"
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
ssender = SmsSingleSender(appid, appkey)
params = ["1234", ]
try:
result = ssender.send_with_param(86, phone_numbers[0],
template_id, params, sign=sms_sign, extend="", ext="")
except HTTPError as e:
print(e)
print(result)
验证码为:{1},您正在登录,若非本人操作,请勿泄露。
params = ["1234"] 中的列表元素会依次替换 模板内容中的{}.
* 3. 运行程序测试
发送成功之后会提示:
{'result': 0, 'errmsg': 'OK', 'ext': '', 'sid': '2640:241303963116531302631655411', 'fee': 1, 'isocode': 'CN'}
* 4. 手机收到短信(有时很墨迹)
4.4 短信服务封装
* 1. 在项目名目录/lib下新建tx_send_mes包
* 2. 在项目名目录/lib/tx_send_mes包下新建 settings.py文件, 将必要参数写在这个文件中.
appid = 1400682819
appkey = "87971852ee0862096105de36b05cb1d1"
phone_numbers = ["自己的手机号码", ]
template_id = 1410883
sms_sign = "Python梦想空间"
* 3. 在项目名目录/lib/tx_send_mes包下新建 send_mes.py文件, 将必要参数写在这个文件中.
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from .settings import *
from random import randint
from utils.logger import log
def get_code(num):
code = ''
for i in range(num):
code += str(randint(0, 9))
return code
def send_mes(phone, code):
ssender = SmsSingleSender(appid, appkey)
params = [code, 5]
try:
result = ssender.send_with_param(86, phone,
template_id, params, sign=sms_sign, extend="", ext="")
if result.get('result') != 0:
return False
return True
except HTTPError as e:
log.error(f'当前手机号{phone}, 错误提示: {e}.')
* 4. 在项目名目录/lib/tx_send_mes包下 __init__.py文件中导入模块
from .send_mes import get_code
from .send_mes import send_mes
4.5 短信服务接口
Django的缓存写入数据
cache.set('键', 值, 过期时间/秒)
* 1. 在定义配置文件settings/const.py 中定义Django缓存手机验证码的键(前缀)
完成格式: 前缀_手机号 settings.PHONE_CACHE_KEY % phone
PHONE_CACHE_KEY = 'sms_cache_%s'
* 2. 短信服务接口发送成功, 放回发送成功的提示信息, 并将验证码写入到Django缓存中
class SMSInterface(ViewSet):
@action(methods=['GET'], detail=False)
def sms_interface(self, request):
phone = request.query_params.get('phone')
is_exist = {'is_send': False}
if not re.match('^1[3-9][0-9]{9}$', phone):
return ResponseDataFormat(code=400, msg='手机号码不合法!', data=is_exist)
code = get_code(4)
is_send = send_mes(phone, code)
if not is_send:
return ResponseDataFormat(code=400, msg='验证码发送不成功!', data=is_exist)
cache.set(settings.PHONE_CACHE_KEY % phone, code, 300)
is_exist = {'is_send': True}
return ResponseDataFormat(code=200, msg='验证码发送成功!', data=is_exist)
* 3. 短信接口频率限制, 在apps/user/下新建throttling.py 文件
from rest_framework.throttling import SimpleRateThrottle
class SMSThrottling(SimpleRateThrottle):
def get_cache_key(self, request, view):
phone = request.query_params.get('phone')
return self.cache_format % {'scope': 'sms', 'ident': phone}
from .throttling import SMSThrottling
class SMSInterface(ViewSet):
throttle_classes = [SMSThrottling, ]
....
REST_FRAMEWORK = {
...
'DEFAULT_THROTTLE_RATES': {'sms': '1/m'}
}
* 4. 路由配置
只需要添加 router.register('', views.LoginView, 'send') 即可
from django.urls import path, re_path, include
from user import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('', views.LoginView, 'login')
router.register('', views.SMSInterface, 'send')
urlpatterns = [
re_path('exception_log/', views.ExceptionLog.as_view()),
path('', include(router.urls)),
]
* 5. 接口测试
http://127.0.0.1:8000/user/sms_interface/?phone=18177
4.6 短信登入接口
使用Navicat将手机改为自己的手机号码
1. 定义模型序列化器
在apps/user/serializer.py 中写模型序列化类
class CodeModelSerializer(serializers.ModelSerializer):
code = serializers.CharField()
class Meta:
model = models.User
fields = ['phone', 'code']
def validate(self, attrs):
phone = attrs.get('phone')
code = attrs.get('code')
user_obj = self._get_user_obj(phone, code)
token = self._get_token(user_obj)
self._context['token'] = token
self._context['username'] = user_obj.username
return attrs
@staticmethod
def _get_user_obj(phone, code):
if not re.match('^1[3-9][0-9]{9}$', phone):
raise ValidationError('手机号码格式不正确!')
load_code = cache.get(settings.PHONE_CACHE_KEY % phone)
if load_code != code:
raise ValidationError('验证码不正确!')
user_obj = models.User.objects.filter(phone=phone).first()
if not user_obj:
raise ValidationError('该手机号没有注册!')
return user_obj
@staticmethod
def _get_token(user_obj):
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
payload = jwt_payload_handler(user_obj)
token = jwt_encode_handler(payload)
return token
2. 短信登录接口
class LoginView(ViewSet):
...
@action(methods=['POST'], detail=False)
def code_login(self, request):
from user.serializer import CodeModelSerializer
ser = CodeModelSerializer(data=request.data)
ser.is_valid(raise_exception=True)
token = ser.context['token']
username = ser.context['username']
return ResponseDataFormat(username=username, token=token)
3. 接口测试
使用Postman测试,
获取code: http://127.0.0.1:8000/user/sms_interface/?phone=18177 获取验证码
登入测试: http://127.0.0.1:8000/user/code_login/ 在body体中填写表单
* 1. 输入错误的验证码(验证码过期)
* 2. 输入错误的手机号
* 3. 输入正确的手机号与验证码
4.7 前端登入
1.校验手机号
输入手机号绑定失去焦点事件, 前端校验手机号的格式是否正确.
前端校验成功之后, 再将手机提交到后端, 再次校验手机号码.
>
<el-input
placeholder="手机号"
...
@blur="check_mobile">
</el-input>
check_mobile() {
if (!this.mobile) return;
if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
this.$message({
message: '手机号有误',
type: 'warning',
duration: 2000,
onClose: () => {
this.mobile = '';
}
});
return false
}
this.$axios.get(this.$settings.base_url + '/user/inquire_phone/', {params: {phone: this.mobile}}).then(response => {
if (response.data.data.is_exist) {
this.is_send = true;
} else {
this.$message({
message: response.data.msg,
type: 'warning',
duration: 2000,
})
}
})
},
url路由拼接成
get(this.$settings.base_url + '/user/inquire_phone/?phone=', + this.mobile)
(this.$settings.base_url + '/user/inquire_phone/', {params: {phone: this.mobile}})
使用params参数
两种方式都可以拼接路由: https:127.0.0.1:8000/user/inquire_phone/?xx=xx
2. 发送验证码
限制一分钟只能发送一条短信.
<span class="sms" @click="send_sms">{{ sms_interval }}</span>
send_sms() {
if (!this.is_send) return;
this.is_send = false;
this.$axios.get(this.$settings.base_url + '/user/sms_interface/', {params: {phone: this.mobile}}).then(response => {
if (response.data.data.is_send) {
this.$message({
message: response.data.msg,
type: 'success',
duration: 2000,
})
}
})
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);
},
3. 验证码登入
为登入按键绑定请求, 登入成功之后通过父传值子修改登入状态. 在将用户名和token写入cookies中.
<el-button type="primary" @click="code_login">登录</el-button>
code_login() {
if (!(this.mobile && this.sms)) {
this.$message({
message: '手机号或验证码没有输入!',
type: 'warning',
duration: 2000,
})
}
this.$axios.post(this.$settings.base_url + '/user/code_login/', {phone: this.mobile, code: this.sms}).then(
response => {
console.log(response.data)
if (response.data.code === 200) {
this.$cookies.set('username', response.data.username)
this.$cookies.set('token', response.data.token)
this.$emit('close')
this.$emit('login_status')
}
}
)
}
4. 测试
手机号不正确, 将手机号码清除.
登入验证(type=password 隐藏一下手机号)
4.8 前后端提交到远端
在Terminai中输入git命令
1. 前端
PS D:\vue\luffy_vue> git add .
PS D:\vue\luffy_vue> git commit -m '完成登入'
PS F:\synchro\Project\luffy> git pull origin dev
PS F:\synchro\Project\luffy> git push origin dev
2. 后端
PS F:\synchro\Project\luffy> git add .
PS F:\synchro\Project\luffy> git commit -m '完成手机登入,验证码登入功能'
PS F:\synchro\Project\luffy> git pull origin dev
PS F:\synchro\Project\luffy> git push origin dev
5. 注册接口
5.1 注册序列化器
class ResponseModelSerializer(serializers.ModelSerializer):
code = serializers.CharField(write_only=True)
class Meta:
model = models.User
fields = ['phone', 'password', 'code']
extra_kwargs = {
'password': {'min_length': 6, 'max_length': 18, 'write_only': True},
}
def validate(self, attrs):
phone = attrs.get('phone')
code = attrs.get('code')
self._is_register(phone, code)
attrs['username'] = phone
return attrs
@staticmethod
def _is_register(phone, code):
if not re.match('^1[3-9][0-9]{9}$', phone):
raise ValidationError('手机号码格式不正确!')
load_code = cache.get(settings.PHONE_CACHE_KEY % phone)
if load_code != code:
raise ValidationError('验证码不正确!')
user_obj = models.User.objects.filter(phone=phone)
if user_obj:
raise ValidationError('该手机号以注册!')
def create(self, validated_data):
validated_data.pop('code')
user_obj = models.User.objects.create_user(**validated_data)
return user_obj
5.2 注册视图类
class Register(ViewSet):
@action(methods=['POST', ], detail=False)
def phone_register(self, request):
from user.serializer import ResponseModelSerializer
ser = ResponseModelSerializer(data=request.data)
ser.is_valid(raise_exception=True)
user_obj = ser.save()
return ResponseDataFormat(msg='注册成功', username=user_obj.username)
5.3 注册路由
from django.urls import path, re_path, include
from user import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('', views.LoginView, 'login')
router.register('', views.SMSInterface, 'send')
router.register('', views.Register, 'register')
urlpatterns = [
re_path('exception_log/', views.ExceptionLog.as_view()),
path('', include(router.urls)),
]
5.4 前端注册页面
1. 校验手机号
输入手机号绑定失去焦点事件, 前端校验手机号的格式是否正确.
前端校验成功之后, 再将手机提交到后端, 再次校验手机号码.
<el-input
placeholder="手机号"
...
@blur="check_mobile">
</el-input>
check_mobile() {
if (!this.mobile) return;
if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
this.$message({
message: '手机号有误',
type: 'warning',
duration: 2000,
onClose: () => {
this.mobile = '';
}
});
return false
}
this.$axios.get(this.$settings.base_url + '/user/inquire_phone/', {params: {phone: this.mobile}}).then(response => {
if (response.data.data.is_exist) {
this.$message({
message: '此号码已经注册可以登入.',
type: 'success',
duration: 2000,
})
this.go_login()
} else {
this.is_send = true;
this.$message({
message: '此号码可以注册.',
type: 'success',
duration: 2000,
})
}
})
},
2. 发送验证码
只要填写了手机号, 手机号码没有问题就点击获取验证码.
密码在点击注册时校验, 必填的.
<span class="sms" @click="send_sms">{{ sms_interval }}</span>
send_sms() {
if (!this.is_send) return;
this.is_send = false;
this.$axios.get(this.$settings.base_url + '/user/sms_interface/', {params: {phone: this.mobile}}).then(response => {
if (response.data.data.is_send) {
this.$message({
message: response.data.msg,
type: 'success',
duration: 2000,
})
}
})
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);
},
3. 注册用户
手机号, 密码, 验证码必须填写.
<el-input>
placeholder="密码 6-18位"
</el-input>
<el-button type="primary" @click="register">注册</el-button>
register() {
if (!(this.mobile && this.sms && this.password)) {
this.$message({
message: '你有信息没有填写.',
type: 'warning',
duration: 2000,
})
}
this.$axios.post(this.$settings.base_url + '/user/phone_register/', {
phone: this.mobile,
code: this.sms,
password: this.password
}).then(response => {
if (response.data.code === 200) {
this.$cookies.set('username', response.data.username)
this.$cookies.set('token', response.data.token)
this.$emit('close')
this.$emit('login_status')
}
})
}
<Register v-if="is_register" @close="close_register" @login_status="loginStatus" @go="put_login"/>
4.测试
修改一下短信接口, 发短信要钱的, 注册发送短信接口, 等项目写完了在把注释取消.
class SMSInterface(ViewSet):
throttle_classes = [SMSThrottling, ]
@action(methods=['GET'], detail=False)
def sms_interface(self, request):
phone = request.query_params.get('phone')
is_exist = {'is_send': False}
if not re.match('^1[3-9][0-9]{9}$', phone):
return ResponseDataFormat(code=400, msg='手机号码不合法!', data=is_exist)
code = get_code(4)
print(code)
cache.set(settings.PHONE_CACHE_KEY % phone, code, 300)
is_exist = {'is_send': True}
return ResponseDataFormat(code=200, msg='验证码发送成功!', data=is_exist)
5.5 前后端提交到远端
1. 前端
PS D:\vue\luffy_vue> git add .
warning: LF will be replaced by CRLF in src/App.vue.
The file will have its original line endings in your working directory
PS D:\vue\luffy_vue> git commit -m '注册接口完成'
[dev bea5a2f] 注册接口完成
3 files changed, 82 insertions(+), 8 deletions(-)
PS D:\vue\luffy_vue> git pull origin dev
From gitee.com:python_21/luffy_vue
* branch dev -> FETCH_HEAD
Already up to date.
PS D:\vue\luffy_vue> git push origin dev
Enumerating objects: 13, done.
Counting objects: 100% (13/13), done.
Delta compression using up to 12 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 1.94 KiB | 995.00 KiB/s, done.
Total 7 (delta 5), reused 0 (delta 0), pack-reused 0
remote: Powered by GITEE.COM [GNK-6.3]
To gitee.com:python_21/luffy_vue.git
2c798be..bea5a2f dev -> dev
2. 后端
PS F:\synchro\Project\luffy> git add .
PS F:\synchro\Project\luffy> git commit -m '注册接口完成'
[dev 13d5a8c] 注册接口完成
11 files changed, 162 insertions(+), 15 deletions(-)
rewrite luffy/apps/home/__pycache__/views.cpython-38.pyc (63%)
rewrite luffy/apps/user/__pycache__/serializer.cpython-38.pyc (61%)
rewrite luffy/apps/user/__pycache__/urls.cpython-38.pyc (91%)
PS F:\synchro\Project\luffy> git pull origin dev
From gitee.com:python_21/luffy
* branch dev -> FETCH_HEAD
Already up to date.
PS F:\synchro\Project\luffy> git push origin dev
Enumerating objects: 40, done.
Counting objects: 100% (40/40), done.
Delta compression using up to 12 threads
Compressing objects: 100% (21/21), done.
Writing objects: 100% (22/22), 8.27 KiB | 529.00 KiB/s, done.
Total 22 (delta 16), reused 0 (delta 0), pack-reused 0
remote: Powered by GITEE.COM [GNK-6.3]
To gitee.com:python_21/luffy.git
1d20d39..13d5a8c dev -> dev
|