一、修改上篇博客的BUG
上一篇推理博客中有两个小彩蛋
- 用的是
authenticate
只能通过用户名密码拿用户,不能用手机号moble
和邮箱email
- 修改:直接拿用户点出来
- 再做
if
判断
bug信息
第二个小彩蛋
- 用
ValidationError
返回信息不对,原因是detail
没取出来 - 更换成
APIException
,将_get_token
也raise APIException
出去
二、sdk知识补充
- 硬件厂商提供的sdk是
dll文件(dll文件就是用C语言、GO语言写完编译成的动态链接库文件)
- 类似于咱python主程序调包,调用包里的东西
三、登录注册模态框分析
如果是跳转新的页面
- 路由中配置一个路由
- 写一个视图组件
逻辑
- 写个Login组件,主页面绑定登录按钮
- login穿header,子传父,写个自定义组件
Login.vue
<template>
<div class="login">
<span @click="handleClose">X</span>
</div>
</template>
<script>
export default {
name: "Login",
methods:{
handleClose(){
this.$emit('close')
}
}
}
</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);
}
</style>
Header.vue
<div class="right-part">
<div>
<span @click="goLogin">登录</span>
<span class="line">|</span>
<span>注册</span>
</div>
<Login v-if="loginShow" @close="closeLogin"></Login>
</div>
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
loginShow: 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
},
closeLogin() {
this.loginShow = false
}
},
created() {
sessionStorage.url_path = this.$route.path
this.url_path = this.$route.path
},
components: {
Login
}
}
四、登录注册前端页面复制
- i标签就是叉号,剩下的样式
div标签
包着
<i class="el-icon-close" @click="close_register"></i>
- 点击事件 密码登录和短信登录
- 两个el-form表单,里面各包含着两个
input框
- 立即注册
代码展示
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>
Header.vue
<template>
<div class="header">
<div class="slogan">
<p>人终向前走 | 花自向阳开 </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>
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>
五、腾讯短信功能二次封装
- 搜短信的产品文档
- 找
SDK下载
的python文档
- SDK的python地址:
https://cloud.tencent.com/document/product/382/43196
使用步骤
- 下载模块:
pip3 install tencentcloud-sdk-python
下个脚本测一下能不能发短信
- 应用列表ID腾讯短信创建app把app的id号复制过来 地址:
https://console.cloud.tencent.com/smsv2/app-manage
- 签名内容
- 模板管理的模板ID号
- 根据短信的模板内容需要上传两个参数
- 运行跑起来就可以了
代码展示
# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
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("AKIDobM4oU6miVAbvHcn15xiIj061jEUdaQ4", "W8VcYFm8FAtXyCFKExUq481kIcjgS1NW")
httpProfile = HttpProfile()
httpProfile.reqMethod = "POST" # post请求(默认为post请求)
httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒)
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 = "1400763090" # 腾讯短信创建app把app的id号复制过来https://console.cloud.tencent.com/smsv2/app-manage
# 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
# 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
req.SignName = "关于金鹏公众号"
# 模板 ID: 必须填写已审核通过的模板 ID
# 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
req.TemplateId = "1603526"
# 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
req.TemplateParamSet = ["515",'628']
# 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
# 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
req.PhoneNumberSet = ["+8615647697835"]
# 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
req.SessionContext = ""
req.ExtendCode = ""
req.SenderId = ""
resp = client.SendSms(req)
# 输出json格式的字符串回包
print(resp.to_json_string(indent=2))
except TencentCloudSDKException as err:
print(err)
注意项:
里面的公钥密钥不要泄露,不然别人能看见代码,这个仅供展示,可在腾讯云里禁用重新创建
把发送短信封装成包
- 后期别的项目,也要使用发送短信——只要把包copy到项目中即可,直接导入就能用
- 封装包:目录结构
- 创建
send_tx_sms
包名__init__.py
settings.py
配置文件sms.py
核心文件
- 创建
- sms里先写个获取n位的随机数组验证码的函数,用一下
random模块
,for循环返回就可
def get_code(num=4):
code = ''
for i in range(num):
random_num = random.randint(0, 9)
code += str(random_num)
return code
- 写个发送验证码的函数,正常是写保存的,但是这个我们要做的是包,就不写保存传个参数
code
自己保存 - settings里配置一些后期修改的信息
注意配置文件的密钥一定是最新的,TMD血的教训,不然报全局异常都不知道去哪找!!!
__init__.py
from .sms import get_code,send_sms_by_phone
settings.py
# 发送短信相关的配置信息
SECRET_ID = 'AKIDobM4oU6miVAbvHcn15xiIj061jEUdaQ4'
SECRET_KEY = 'W8VcYFm8FAtXyCFKExUq481kIcjgS1NW'
APP_ID = '1400763090'
SIGN_NAME='关于金鹏公众号'
TEMPLATE_ID='1603526'
sms.py
# 核心代码
import random
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
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
# 获取n位随机数组验证码的函数
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" # post请求(默认为post请求)
httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒)
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 # 腾讯短信创建app把app的id号复制过来https://console.cloud.tencent.com/smsv2/app-manage
# 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
# 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
req.SignName = settings.SIGN_NAME
# 模板 ID: 必须填写已审核通过的模板 ID
# 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
req.TemplateId = settings.TEMPLATE_ID
# 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
req.TemplateParamSet = [code, '1']
# 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
# 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
req.PhoneNumberSet = ["+86" + mobile, ]
# 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
req.SessionContext = ""
req.ExtendCode = ""
req.SenderId = ""
resp = client.SendSms(req)
# 输出json格式的字符串回包
# 字符串类型
print(type(resp.to_json_string(indent=2)))
return True
except TencentCloudSDKException as err:
return False
六、短信验证码接口
前端通过get请求向http://127.0.0.1:8000/api/v1/userinfo/user/send_sms/?mobil=手机号
- 网址获取手机号,做一个正则的if判断(严谨一点)
- 保存验证码,能存不能丢后期要求,django自带的缓存cache导入即可
from django.core.cache import cache
然后根据手机号拿code - 放在内存中了,只要重启就没了——>后期学完
redis
,放到redis中,重启项目,还在
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()
print(code) # 保存验证码---》能存,不能丢,后期能取---》缓存--》django自带缓存框架
# 放在内存中了,只要重启就没了----》后期学完redis,放到redis中,重启项目,还在
cache.set('sms_code_%s' % mobile, code)
# cache.get('sms_code_%s'%mobile)
res = send_sms_by_phone(mobile, code)
if res:
return APIResponse(msg='发送短信成功')
else:
# raise APIException('发送短信失败')
return APIResponse(msg='发送短信失败', code=101)
else:
return APIResponse(msg='手机号不合法', code=102)
七、短信登录接口
手机号+验证码——>写成{mobile:手机号,code:验证码}
——>朝这个地址 /api/v1/userinfo/user/mobile_login/
发送post请求
- 在序列化类中写个
UserMobileLoginSerializer
- 检验mobile和code,code不是userinfo的字段,影射不出来,在上面重写一下
- 取出手机号和验证码校验,记住从缓存中取出code进行校验。
- 做判断,签发token
- 跟之前邮箱和用户名一样的坑,重写mobile因为里面有个uniqe=True,
mobile = serializers.CharField()
- 写个if判断,通过判断请求的
action
是mul_loginUser
还是mobile_login
,判断返回的是MulLoginSerializer
和UserMobileLoginSerializer
def get_serializer(self, data):
# 判断如果请求的action是:mul_login,返回UserMulLoginSerializer
# 判断如果请求的action是:mobile_login,返回UserMobileLoginSerializer
if self.action == 'mul_login':
return UserMulLoginSerializer(data=data)
else:
return UserMobileLoginSerializer(data=data)
- 写个
def common_login(self, request):
,把签发的一堆放一块
def common_login(self, request):
ser = self.get_serializer(data=request.data)
ser.is_valid(raise_exception=True)
token = ser.context.get('token')
username = ser.context.get('username')
icon = ser.context.get('icon')
return APIResponse(token=token, username=username, icon=icon)
- 一个验证码能一直用,写个验证码置为空
cache.set
cache.set('sms_code_%s' % mobile, code)
代码展示
user/views
from django.shortcuts import render
# Create your views here.
# post--->查询--->自动生成路由,action装饰器可以在视图类中写多个函数
from rest_framework.viewsets import ViewSet, GenericViewSet, ViewSetMixin
from rest_framework.decorators import action
from .models import UserInfo
from .serializer import UserMulLoginSerializer, UserMobileLoginSerializer
import re
from utils.response import APIResponse
from rest_framework.exceptions import APIException
from libs.send_tx_sms import get_code, send_sms_by_phone
from django.core.cache import cache
class UserView(ViewSet):
def get_serializer(self, data):
# 判断如果请求的action是:mul_login,返回UserMulLoginSerializer
# 判断如果请求的action是:mobile_login,返回UserMobileLoginSerializer
if self.action == 'mul_login':
return UserMulLoginSerializer(data=data)
else:
return UserMobileLoginSerializer(data=data)
def common_login(self, request):
ser = self.get_serializer(data=request.data)
ser.is_valid(raise_exception=True)
token = ser.context.get('token')
username = ser.context.get('username')
icon = ser.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='手机号存在') # {code:100,msg:手机号存在}
except Exception as e:
raise APIException('手机号不存在') # {code:999,msg:手机号不存在}
@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()
print(code) # 保存验证码---》能存,不能丢,后期能取---》缓存--》django自带缓存框架
# 放在内存中了,只要重启就没了----》后期学完redis,放到redis中,重启项目,还在
cache.set('sms_code_%s' % mobile, code)
# cache.get('sms_code_%s'%mobile)
res = send_sms_by_phone(mobile, code)
if res:
return APIResponse(msg='发送短信成功')
else:
# raise APIException('发送短信失败')
return APIResponse(msg='发送短信失败', code=101)
else:
return APIResponse(msg='手机号不合法', code=102)
面试题
1、什么是python的深浅copy?
深拷贝:拷贝对象以及其子对象(copy.deepcopy())
浅拷贝:只拷贝父对象,不拷贝子对象(copy.copy())
2、__new__和__init__的区别?
1.__new__是在实例创建之前被调用的,用于创建实例,然后返回该实例对象,是个静态方法。
2.__init__是当实例对象创建完成后被调用的,用于初始化一个类实例,是个实例方法。
3、__new__至少要有一个参数cls,且必须要有返回值,返回的是实例化出来的实例。
4、__init__有一个参数self,就是这个__new__返回的实例,__init__在__new__基础上完成一些其他初始化的动作,__init__不需要有返回值
3、python 是值传递还是引用传递? 是引用传递
Python参数传递统一使用的是 引用传递方式。
因为Python对象分为可变对象(list,dict,set等)和不可变对象(number,string,tuple等),
当传递的参数是可变对象的引用时,因为可变对象的值可以修改,
因此可以通过修改参数值而修改原对象,这类似于C语言中的引用传递;
当传递的参数是不可变对象的引用时,虽然传递的是引用,
参数变量和原变量都指向同一内存地址,但是不可变对象无法修改,所以参数的重新赋值不会影响原对象
4、python 可变与不可变?
可变、不可变是指内存中的那块空间是否可以被改变
可变类型,创建后可以继续修改对象的内容(值) 比如:字典,列表
不可变类型,一旦创建就不可修改的对象(值) 比如:数字,字符串,元组 当内容发生修改,计算机重新分配一块内存空间
标签:code,return,mobile,sms,luffy,import,login,商城,第七天
From: https://www.cnblogs.com/scx-xiaochun/p/16886737.html