一、登录注册页面
<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>
</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>
</div>
</template>
<script>
import login from "@/components/login";
import Register from "@/components/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;
},
goLogin() {
this.loginShow = true
},
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: {
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>
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.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>
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.1 安装腾讯云SDK
https://cloud.tencent.com/document/product/382/43196
pip install --upgrade tencentcloud-sdk-python
![]()
2.2 脚本测试发送短信
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
cred = credential.Credential("这里填写你的访问密钥", "这里填写你的访问密钥")
httpProfile = HttpProfile()
httpProfile.reqMethod = "POST"
httpProfile.reqTimeout = 30
httpProfile.endpoint = "sms.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.signMethod = "TC3-HMAC-SHA256"
clientProfile.language = "en-US"
clientProfile.httpProfile = httpProfile
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
req = models.SendSmsRequest()
req.SmsSdkAppId = "1400763362"
req.SignName = "dy12138个人公众号"
req.TemplateId = "1603763"
req.TemplateParamSet = ["6787",'60']
req.PhoneNumberSet = ["+86这里写手机号"]
req.SessionContext = ""
req.ExtendCode = ""
req.SenderId = ""
resp = client.SendSms(req)
print(resp.to_json_string(indent=2))
except TencentCloudSDKException as err:
print(err)
2.3 短信功能二次封装V3
目录结构
libs
tx_sms
__init__.py
settings.py
sms.py
libs/init.py
from .sms import get_code, send_sms_by_phone
libs/settings.py
SECRET_ID = '这里填写你的访问密钥'
SECRET_KEY = '这里填写你的访问密钥'
APP_ID = '1400763362'
SIGN_NAME = '公众号'
TEMPLATE_ID = '1603763'
libs/sms.py
import random
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from . import settings
def get_code(num=4):
code = ''
for i in range(num):
random_num = random.randint(0, 9)
code += str(random_num)
return code
def send_sms_by_phone(mobile, code):
try:
cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)
httpProfile = HttpProfile()
httpProfile.reqMethod = "POST"
httpProfile.reqTimeout = 30
httpProfile.endpoint = "sms.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.signMethod = "TC3-HMAC-SHA256"
clientProfile.language = "en-US"
clientProfile.httpProfile = httpProfile
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
req = models.SendSmsRequest()
req.SmsSdkAppId = settings.APP_ID
req.SignName = settings.SIGN_NAME
req.TemplateId = settings.TEMPLATE_ID
req.TemplateParamSet = [code, '10']
req.PhoneNumberSet = ["+86" + mobile, ]
req.SessionContext = ""
req.ExtendCode = ""
req.SenderId = ""
resp = client.SendSms(req)
print(resp.to_json_string(indent=2))
return True
except TencentCloudSDKException as err:
return False
2.4 验证测试
user/views.py
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .serializer import UserMulLoginSerializer
from utils.response import APIResponse
from .models import UserInfo
from rest_framework.exceptions import APIException
from libs.tx_sms import get_code, send_sms_by_phone
import re
from django.core.cache import cache
class UserView(ViewSet):
@action(methods=['GET'], detail=False)
def send_sms(self, request):
code = get_code()
res = send_sms_by_phone('这里填写手机号', code)
if res:
return APIResponse(msg='短信发送成功')
else:
raise APIException('短信发送失败')

三、短信验证码接口
3.1 user/views.py
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .serializer import UserMulLoginSerializer
from utils.response import APIResponse
from .models import UserInfo
from rest_framework.exceptions import APIException
from libs.tx_sms import get_code, send_sms_by_phone
import re
from django.core.cache import cache
class UserView(ViewSet):
@action(methods=['GET'], detail=False)
def send_sms(self, request):
mobile = request.query_params.get('mobile')
if re.match(r'^1[3-9][0-9]{9}$', mobile):
code = get_code()
cache.set('sms_code_%s' % mobile, code)
res = send_sms_by_phone(mobile, code)
if res:
return APIResponse(msg='短信发送成功')
else:
raise APIException('短信发送失败')
else:
return APIResponse(msg='手机号输入不合法', code=202)
3.2 验证测试

四、短信登录接口
4.1 user/serializer.py
from rest_framework import serializers
from .models import UserInfo
import re
from rest_framework.exceptions import APIException
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from django.core.cache import cache
class UserMulLoginSerializer(serializers.ModelSerializer):
username = serializers.CharField()
class Meta:
model = UserInfo
fields = ['username', 'password']
def _get_user(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if re.match(r'^1[3-9][0-9]{9}$', username):
user = UserInfo.objects.filter(mobile=username).first()
elif re.match(r'^.+@.+$', username):
user = UserInfo.objects.filter(email=username).first()
else:
user = UserInfo.objects.filter(username=username).first()
if user and user.check_password(password):
return user
else:
raise APIException('用户名或密码错误')
def _get_token(self, user):
try:
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
except Exception as e:
raise APIException(str(e))
def validate(self, attrs):
user = self._get_user(attrs)
token = self._get_token(user)
self.context['token'] = token
self.context['username'] = user.username
self.context['icon'] = 'http://127.0.0.1:8000/media/' + str(user.icon)
return attrs
class UserMobLieLoginSerializer(serializers.ModelSerializer):
mobile = serializers.CharField()
code = serializers.CharField()
class Meta:
model = UserInfo
fields = ['mobile', 'code']
def _get_user(self, attrs):
mobile = attrs.get('mobile')
code = attrs.get('code')
old_code = cache.get('sms_code_%s' % mobile, code)
cache.set('sms_code_%s' % mobile, '')
if code == old_code:
user = UserInfo.objects.filter(mobile=mobile).first()
return user
raise APIException('验证码错误')
def _get_token(self, user):
try:
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
except Exception as e:
raise APIException(str(e))
def validate(self, attrs):
user = self._get_user(attrs)
token = self._get_token(user)
self.context['token'] = token
self.context['username'] = user.username
self.context['icon'] = 'http://127.0.0.1:8000/media/' + str(user.icon)
return attrs
4.2 user/views.py
from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .serializer import UserMulLoginSerializer, UserMobLieLoginSerializer
from utils.response import APIResponse
from .models import UserInfo
from rest_framework.exceptions import APIException
from libs.tx_sms import get_code, send_sms_by_phone
import re
from django.core.cache import cache
class UserView(ViewSet):
def get_serializer(self, data):
if self.action == 'mul_login':
return UserMulLoginSerializer(data=data)
else:
return UserMobLieLoginSerializer(data=data)
def common_login(self, request):
res = self.get_serializer(data=request.data)
res.is_valid(raise_exception=True)
token = res.context.get('token')
username = res.context.get('username')
icon = res.context.get('icon')
return APIResponse(token=token, username=username, icon=icon)
@action(methods=['POST'], detail=False)
def mul_login(self, request):
return self.common_login(request)
@action(methods=['POST'], detail=False)
def mobile_login(self, request):
return self.common_login(request)
@action(methods=['GET'], detail=False)
def mobile(self, request):
try:
mobile = request.query_params.get('mobile')
UserInfo.objects.get(mobile=mobile)
return APIResponse(msg='该手机号存在')
except Exception as e:
raise APIException('该手机号不存在')
@action(methods=['GET'], detail=False)
def send_sms(self, request):
mobile = request.query_params.get('mobile')
if re.match(r'^1[3-9][0-9]{9}$', mobile):
code = get_code()
cache.set('sms_code_%s' % mobile, code)
res = send_sms_by_phone(mobile, code)
if res:
return APIResponse(msg='短信发送成功')
else:
raise APIException('短信发送失败')
else:
return APIResponse(msg='手机号输入不合法', code=202)
4.3 验证测试


五、扩展知识
最直观的理解就是:
1.深拷贝,拷贝的程度深,自己新开辟了一块内存,将被拷贝内容全部拷贝过来了;
2.浅拷贝,拷贝的程度浅,只拷贝原数据的首地址,然后通过原数据的首地址,去获取内容。
两者的优缺点对比:
(1)深拷贝拷贝程度高,将原数据复制到新的内存空间中。改变拷贝后的内容不影响原数据内容。但是深拷贝耗时长,且占用内存空间。
(2)浅拷贝拷贝程度低,只复制原数据的地址。其实是将副本的地址指向原数据地址。修改副本内容,是通过当前地址指向原数据地址,去修改。所以修改副本内容会影响到原数据内容。但是浅拷贝耗时短,占用内存空间少。
当内层为可变数据类型时,深拷贝后内层外层地址均发生改变。当内层为不可变数据类型时,外层不管是可变还是不可变数据类型,使用深拷贝,都不会改变内层地址,只会在外层为可变数据类型时,改变外层地址。
使用浅拷贝是只能在外层数据类型为可变数据类型时,才能改变外层地址。而内层地址,无论是否为可变数据类型还是不可变数据类型,使用浅拷贝都不会改变内层数据类型地址。
__new__()用于创建实例,而__init__()则负责初始化实例
__new__方法:类级别的方法 、 __init__方法:实例级别的方法
1、__new__ 至少要有一个参数cls,代表当前类,此参数在实例化时由Python解释器自动识别
2、__new__ 必须要有返回值,返回实例化出来的实例,可以return 父类__new__出来的实例 或者直接是object的__new__出来的实例
3、__int__ 有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其它初始化的动作,__init__不需要返回值
4、如果__new__创建的是当前类的实例,会自动调用init函数通过return调用的__new__函数的第一个参数cls来保证是当前类实例;如果是其它类的类名实际创建返回的也是其他类的实例,不会调用当前类的__init__,也不会调用其他类的__init__
Python参数传递统一使用的是引用传递方式。因为Python对象分为可变对象(list,dict,set等)和不可变对象(number,string,tuple等),当传递的参数是可变对象的引用时,因为可变对象的值可以修改,因此可以通过修改参数值而修改原对象,这类似于C语言中的引用传递;当传递的参数是不可变对象的引用时,虽然传递的是引用,参数变量和原变量都指向同一内存地址,但是不可变对象无法修改,所以参数的重新赋值不会影响原对象,这类似于C语言中的值传递。
不可变类型的变量在第一次赋值声明的时候,会在内存中开辟一块空间,用来存储这个变量被赋予的值,变量被声明后,变量的值就与开辟的内存空间绑定,我们不能修改存储在内存中的值,当我们想给此变量赋新值时,会开辟一块新的内存空间保存新的值。
不可变数据类型的值变化,地址也会变。
可变类型的变量在第一次赋值声明的时候,也会在内存中开辟一块空间,用来存储这个变量被赋予的值。我们能修改存储在内存中的值,当该变量的值发生了改变,它对应的内存地址不发生改变。
可变数据类型变量中的值变化,地址不会变。若对变量进行重新赋值,则变量的地址也会改变。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)