Luffy项目

一、 腾讯云短信开发

# 给手机发送短信---》第三方平台:腾讯云短信----》

# API和SDK,有sdk优先用sdk
# sdk:
    3.0版本,云操作的sdk,不仅仅有发送短信,还有云功能的其他功能
    2.0版本,简单,只有发送短信功能
    
    
    
# 安装sdk
    -方式一:pip install tencentcloud-sdk-python
    -方式二源码安装:
        -下载源码
        -执行 python steup.py install

# 发送短信测试

1、封装发送短信

-libs下:
    send_sms_v3
        __init__.py
        settings.py
        sms.py
        
       
    
# __init__.py
from .sms import get_code,send_sms


# settings.py
SECRET_ID = ''
SECRET_KEY = ''
APP_ID = ''
SIGN_NAME = ''
TEMPLATE_ID = ''

# sms.py
# 生成 n 位数字验证码的函数
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
import json


def get_code(number=4):
    code = ''
    for i in range(number):
        code += str(random.randint(0, 9))  # python 是强类型语言,不同类型运算不允许
    return code


# 发送短信函数
def send_sms(code, mobile):
    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
        req.SignName = settings.SIGN_NAME
        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 = ""
        # 国际/港澳台短信 senderid(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.SenderId = ""
        resp = client.SendSms(req)
        # 输出json格式的字符串回包
        res = json.loads(resp.to_json_string(indent=2))
        if res.get('SendStatusSet')[0].get('Code') == 'Ok':
            return True
        else:
            return False
    except TencentCloudSDKException as err:
        print(err)
        return False

二、登录/注册后端逻辑API编写

1、发送短信验证码接口

class UserView(GenericViewSet):
    serializer_class = UserLoginSerializer
    queryset = User.objects.all().filter(is_active=True)

    
    @action(methods=['POST'], detail=False)
    def send_sms(self, request):
        try:
            mobile = request.data['mobile']
            # 生成验证码
            code = get_code()
            res = send_sms_ss(code, mobile)  # 同步发送,后期可以改成异步  后期学了celery可以加入异步 目前咱们可以使用 多线程
            if res:
                return APIResponse(msg='发送成功')
            else:
                return APIResponse(code=101, msg='发送失败')

        except Exception as e:
            raise APIException(str(e))

2、 短信登录接口

# 前端---》{mobile:122334,code:8888}---->post----》
# 视图类的方法中的逻辑
	1 取出手机号和验证码
    2 校验验证码是否正确(发送验证码接口,存储验证码)
    	-session:根本不用
        -全局变量:不好,可能会取不到,集群环境中
        -缓存:django 自带缓存
            -from django.core.cache import cache
            -cache.set()
            -cache.get()
    3 根据手机号查询用户,如果能查到
    4 签发token
    5 返回给前端
           

2、1.视图类

class UserView(GenericViewSet):
    # class UserView(ViewSetMixin, GenericAPIView):
    serializer_class = UserLoginSerializer
    queryset = User.objects.all().filter(is_active=True)
    # 重写
    def get_serializer_class(self):
        if self.action == 'login_sms':
            return UserMobileLoginSerializer
        else:
            return super().get_serializer_class()



    def _login(self,request,*args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(token=token, username=username)

    @action(methods=['POST'], detail=False)
    def login_sms(self, request, *args, **kwargs):
        return self._login(request)

2、2.序列化类

from .models import User
from rest_framework import serializers
import re
from rest_framework.exceptions import APIException, ValidationError
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 BaseUserSerializer:
    def validate(self, attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        self.context['token'] = token
        self.context['username'] = user.username
        return attrs

    def _get_user(self, attrs):
        raise Exception('你必须重写它')

    def _get_token(self, user):
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token



class UserMobileLoginSerializer(BaseUserSerializer, serializers.ModelSerializer):
    code = serializers.CharField()
    mobile = serializers.CharField()

    class Meta:
        model = User
        fields = ['mobile', 'code']  # code 不是表的字段,要重写 ,mobile 有唯一约束,需要重写
        
        
    def _get_user(self, attrs):
        code = attrs.get('code')
        mobile = attrs.get('mobile')
        # 从缓存中取出
        old_code = cache.get('sms_code_%s' % mobile)
        if old_code and old_code == code:
            # 根据手机号,查到用户
            user = User.objects.filter(mobile=mobile).first()
            if user:
                return user
            else:
                raise APIException('用户不存在')
        else:
            raise APIException('验证码验证失败')

3、短信注册接口

# 前端---》{mobile:1888344,code:8888,password:123}--->post
# 后端  视图类

3、1. 路由

# http://127.0.0.1:8000/api/v1/user/register/   --->post 请求
router.register('register',views.RegisterUserView,'register')

3、2.视图类

class RegisterUserView(GenericViewSet, CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer

    def create(self, request, *args, **kwargs):
        # 使用父类的,会触发序列化,一定要让code只写
        super().create(request, *args, **kwargs)

        # 另一种写法,不用序列化
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # self.perform_create(serializer)
        return APIResponse(msg='注册成功')

3、3.序列化类

class RegisterSerializer(serializers.ModelSerializer):
    # code 不是数据库字段,重写
    code = serializers.CharField(max_length=4, write_only=True)

    class Meta:
        model = User
        fields = ['mobile', 'code', 'password']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):  # 全局钩子
        '''
        1 取出前端传入的code,校验code是否正确
        2 把username设置成手机号(你可以随机生成),用户名如果不传,存库进不去
        3 code 不是数据库的字段,从attrs中剔除
        '''
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('sms_code_%s' % mobile)
        if old_code and old_code == code:
            attrs['username'] = mobile
            attrs.pop('code')
        else:
            raise APIException('验证码验证失败')

        return attrs

    def create(self, validated_data):  # 一定要重写create,因为密码是明文,如果不重写,存入到数据库的也是明文
        # validated_data={username:18888,mobile:18888,password:123}
        # 创建用户
        user = User.objects.create_user(**validated_data)

        # 不要忘了return,后期,ser.data 会使用当前返回的对象做序列化
        return user

三、登录/注册前端页面

1、登录页面

页面分析:

  • 点击首页登录按钮,弹出登录窗口的模态框
  • 点击右上角clos按钮,关闭登录窗口模态框
  • 登录页面包含普通登录、短信登录,点击可以切换
  • 登录完成自动关闭模态框,登录注册按钮变为用户名

Logon.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" @click="login">登录</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 @click="mobile_login" 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;
      // js正则:/正则语法/
      // '字符串'.match(/正则语法/)
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      // 手机号前端校验通过---》开始后端手机号是否存在的校验
      // 后台校验手机号是否已存在
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/check_mobile/?mobile=' + this.mobile,
        method: 'get',
      }).then(response => {
        // code 如果是100,说明手机号存在,登录功能,才能发送短信
        // ==   只比较值是否相等
        // ===  即比较值,又比较类型
        if (response.data.code == 100) {
          this.$message({
            message: '账号正常',
            type: 'success',
            duration: 1000,
          });
          // 发生验证码按钮才可以被点击
          this.is_send = true;
        } else {
          this.$message({
            message: '账号不存在',
            type: 'warning',
            duration: 1000,
            onClose: () => {
              this.mobile = '';
            }
          })
        }
      }).catch(() => {
      });
    },
    send_sms() {
      // this.is_send 如果是false,函数直接结束,就不能发送短信
      if (!this.is_send) return;
      // 按钮点一次立即禁用
      this.is_send = false;

      let sms_interval_time = 60;
      this.sms_interval = "发送中...";

      // 定时器: setInterval(fn, time, args)

      // 往后台发送验证码
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/send_sms/',
        method: 'post',
        data: {
          mobile: this.mobile
        }
      }).then(response => {
        if (response.data.code == 100) { // 发送成功
          // 启动定时器
          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);
        } else {  // 发送失败
          this.sms_interval = "重新获取";
          this.is_send = true;
          this.$message({
            message: '短信发送失败',
            type: 'warning',
            duration: 3000
          });
        }
      }).catch(() => {
        this.sms_interval = "频率过快";
        this.is_send = true;
      })


    },
    login() {
      if (!(this.username && this.password)) {
        this.$message({
          message: '请填好账号密码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/login_mul/',
        method: 'post',
        data: {
          username: this.username,
          password: this.password,
        }
      }).then(response => {
        let username = response.data.username;
        let token = response.data.token;
        this.$cookies.set('username', username, '7d');
        this.$cookies.set('token', token, '7d');
        this.$emit('success', response.data.result);
      }).catch(error => {
        console.log(error.response.data)
      })
    },
    mobile_login() {
      if (!(this.mobile && this.sms)) {
        this.$message({
          message: '请填好手机与验证码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/login_sms/',
        method: 'post',
        data: {
          mobile: this.mobile,
          code: this.sms,
        }
      }).then(response => {
        let username = response.data.username
        let token = response.data.token
        // 放到cookie中,7天过期
        this.$cookies.set('username', username, '7d')
        this.$cookies.set('token', token, '7d')
        // 关闭登录框
        this.$emit('success')
      }).catch(error => {
        console.log(error.response.data)
      })
    }
  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.7);
}

.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、注册页面

<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 @click="register" 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;
      // js正则:/正则语法/
      // '字符串'.match(/正则语法/)
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      // 后台校验手机号是否已存在
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/check_mobile/',
        method: 'get',
        params: {
          mobile: this.mobile
        }
      }).then(response => {
        // 手机号不存在,才能发送短信,才能注册
        if (response.data.code != 100) {
          this.$message({
            message: '欢迎注册我们的平台',
            type: 'success',
            duration: 1500,
          });
          // 发生验证码按钮才可以被点击
          this.is_send = true;
        } else {
          this.$message({
            message: '账号已存在,请直接登录',
            type: 'warning',
            duration: 1500,
          })
        }
      }).catch(() => {
      });
    },
    send_sms() {
      // this.is_send必须允许发生验证码,才可以往下执行逻辑
      if (!this.is_send) return;
      // 按钮点一次立即禁用
      this.is_send = false;

      let sms_interval_time = 60;
      this.sms_interval = "发送中...";

      // 往后台发送验证码
      this.$axios({
        url: this.$settings.BASE_URL + '/user/userinfo/send_sms/',
        method: 'post',
        data: {
          mobile: this.mobile
        }
      }).then(response => {
        if (response.data.code==100) { // 发送成功
          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);
        } else {  // 发送失败
          this.sms_interval = "重新获取";
          this.is_send = true;
          this.$message({
            message: '短信发送失败',
            type: 'warning',
            duration: 3000
          });
        }
      }).catch(() => {
        this.sms_interval = "频率过快";
        this.is_send = true;
      })


    },
    register() {
      if (!(this.mobile && this.sms && this.password)) {
        this.$message({
          message: '请填好手机、密码与验证码',
          type: 'warning',
          duration: 1500
        });
        return false  // 直接结束逻辑
      }

      this.$axios({
        url: this.$settings.BASE_URL + '/user/register/',
        method: 'post',
        data: {
          mobile: this.mobile,
          code: this.sms,
          password: this.password
        }
      }).then(response => {
        this.$message({
          message: '注册成功,3秒跳转登录页面',
          type: 'success',
          duration: 3000,
          showClose: true,
          onClose: () => {
            // 去向成功页面
            this.$emit('success')
          }
        });
      }).catch(error => {
        this.$message({
          message: '注册失败,请重新注册',
          type: 'warning',
          duration: 1500,
          showClose: true,
          onClose: () => {
            // 清空所有输入框
            this.mobile = '';
            this.password = '';
            this.sms = '';
          }
        });
      })
    }
  }
}
</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>