短信的封装

1 登录注册模态框分析

# 如果登录注册是新的页面,比较好做
	-只需要新建两个页面组件---》点击某个按钮--->跳转到页面

1.1 组件通信之 子传父

<template> 
    <div class="login"><span @click="close_login">X</span>
</div> 

</template> 
<script> 
    export default {
        name: "Login", 
        methods: {
            close_login() { 
                // 控制父组件中的is_login变量编程false this.$emit('close_login') 
            } } } 
</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>

2 登录注册前端页面复制

2.0 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>
          <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";
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; // 当前路径存起来   好处是:点刷新后,还是在当前路径下
    },
    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>

2.1 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>

2.2 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>

3 腾讯短信功能二次封装

# 腾讯云官方
	-短信申请:申请签名,申请模板
    -使用官方提供的sdk或者api发送短信
    -如果没有sdk就是用api调用
    -现在有sdk,优先使用sdk,简单---》不同语言封装的包,直接调用包的方法就可以完成相关操作
    - 2.0版本的sdk,3.0版本的sdk
    
    -安装3.0的sdk:pip install tencentcloud-sdk-python   # 腾讯云所有的功能都集成到这个包中了
    -安装2.0的sdk:pip install qcloudsms_py              # 腾讯云短信功能在这个包中

image-20220712120354302

3.1 封装v2版本

init.py

from .sms import get_code,send_sms_v2

settings.py

# 短信应用 SDK AppID
APPID =   # SDK AppID 以1400开头
# 短信应用 SDK AppKey
APPKEY = ""
# 需要发送短信的手机号码

# 短信模板ID,需要在短信控制台中申请
TEMPLATE_ID = 1470213  # NOTE: 这里的模板 ID`7839` 只是示例,真实的模板 ID 需要在短信控制台中申请
# 签名
SMS_SIGN = "咋啦叭呼"  # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请

sms.py

# 生成随机n位验证码的函数
import random

from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from . import settings  # 使用相对导入


def get_code(n=4):
    code = ''
    for i in range(n):
        code += str(random.randint(0, 9))
    return code


# 发送短信的函数
def send_sms(phone, code):
    phone_numbers = [phone, ]
    ssender = SmsSingleSender(settings.APPID, settings.APPKEY)
    params = [code, '1']  # 当模板没有参数时,`params = []`
    try:
        result = ssender.send_with_param(86, phone_numbers[0],
                                         settings.TEMPLATE_ID, params, sign=settings.SMS_SIGN, extend="", ext="")
    except Exception as e:
        return False
    return True


if __name__ == '__main__':
    print(get_code())

3.2 封装v3版本

init.py

from .sms import get_code,send_sms_v2

settings.py

SECRET_ID='AKIDZL2jO2WtBOWaXPE5qV9iKtPvRrCQZiiY'
SECRET_KEY='kKl5FF6oNvLZaR5WklZAZllY9XkneIl2'


APPID = '1400705789'  # SDK AppID 以1400开头
TEMPLATE_ID = '1470213'
# 签名
SMS_SIGN = "咋啦叭呼"


### v3版本的APPID  TEMPLATE_ID  都必须使用str类型,数字类型报错

sms.py

# 生成随机n位验证码的函数
import random

from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from . import settings  # 使用相对导入
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


def get_code(n=4):
    code = ''
    for i in range(n):
        code += str(random.randint(0, 9))
    return code


# 发送短信的函数
def send_sms(phone, 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.APPID
        req.SignName = settings.SMS_SIGN
        req.TemplateId = settings.TEMPLATE_ID
        req.TemplateParamSet = [code, '5']
        req.PhoneNumberSet = ["+86" + phone, ]
        req.SessionContext = ""
        req.ExtendCode = ""
        req.SenderId = ""
        resp = client.SendSms(req)
        # print(resp.to_json_string(indent=2))
        return True
    except TencentCloudSDKException as err:
        # print(err)
        return False


4 短信验证码接口

# post  get  我选择用get
# 前端传入手机号,调用发送短信函数,完成发送短信

路由

# 127.0.0.1:8000/api/v1/user/sms/send_sms
router.register('sms', SMSView, 'sms')

视图类

# from libs import tencent_sms_v2 as tencent_sms
from libs import tencent_sms_v3 as tencent_sms
import re
class SMSView(ViewSet):
    @action(methods=['GET'], detail=False)
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if mobile and re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = tencent_sms.get_code()
            res = tencent_sms.send_sms(mobile, code)
            if res:
                return APIResponse()
            else:
                raise APIException(detail='发送短信失败')
        else:
            raise APIException(detail='手机号有误')

5 短信登录接口

# 前端传入的格式---{mobile:12334455,code:8888}

路由

router.register('sms', SMSView, 'sms')

视图类

class LoginView(GenericViewSet):
    queryset = User.objects.all()
    serializer_class = MulLoginSerializer

    def common_login(self, request):
        ser = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        return APIResponse(token=token, icon=icon)
    # 重写这个方法get_serializer_class,返回什么序列化类,当前用的序列化类就是哪个
    def get_serializer_class(self):
        # 方式一 :通过请求路径来判断,可以
        # if 'mul_login' in self.request.path:
        #     return self.serializer_class
        # else:
        #     return 序列化类

        # 方式二:通过action判断
        if self.action =='sms_login':
            return SMSLoginSerializer
        else:
            return self.serializer_class

    @action(methods=['POST'], detail=False)
    def mul_login(self, request):
        return self.common_login(request)

    @action(methods=['POST'], detail=False)
    def sms_login(self, request):
        return self.common_login(request)

序列化类

class SMSLoginSerializer(serializers.ModelSerializer):
    code = serializers.CharField()  # code不是User表的字段,所以要重写code

    class Meta:
        model = User
        fields = ['mobile', 'code']

    def _check_user(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        # 校验code对不对?从缓存中取出来
        old_code = cache.get('sms_cache_%s' % mobile)
        # 取出来,立马失效
        cache.set('sms_cache_%s' % mobile,'')
        if old_code == code:  # 万能验证码
            user = User.objects.filter(mobile=mobile).first()
            if user:
                return user
            else:
                raise APIException(detail='用户不存在')
        else:
            raise APIException(detail='验证码错误')

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

    def validate(self, attrs):  # 在全局钩子中,校验用户是否登录成功,如果登录成功直接签发token
        # 1 手机号得到user
        user = self._check_user(attrs)
        # 2 user签发token---》签发token
        token = self._get_token(user)
        # 3 把token放到 self 对象中得context属性中
        self.context['token'] = token
        host = self.context.get('request').META['HTTP_HOST']
        self.context['icon'] = 'http://%s/media/%s' % (host, str(user.icon))

        return attrs

6 短信注册接口

# 前端传入数据----》{mobile:1983334,password:123,code:8888}

视图类

class UserView(GenericViewSet, CreateModelMixin):
    serializer_class = UserSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功')

序列化类

class UserSerializer(serializers.ModelSerializer):
    code = serializers.CharField(write_only=True)  # code不是User表的字段,所以要重写code

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

    def validate(self, attrs):
        # 1 校验code是否正确
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get('sms_cache_%s' % mobile)
        if not code == old_code:
            raise APIException(detail='验证码错误')

        # 2 手机号是否被注册过
        if User.objects.filter(mobile=mobile).first():
            raise APIException(detail='该手机号已经被注册')

        # 3 入库前准备---》code字段从attrs中剔除,username必填,手机号就是用户名
        attrs.pop('code')
        attrs['username'] = mobile

        return attrs

    def create(self, validated_data):
        # 因为新增用户,是用create_user新增的,不是使用create新增的
        user = User.objects.create_user(**validated_data)
        return user

路由

router.register('register', UserView, 'register')

问题分析

1 python的深浅copy
深浅拷贝对于不可变类型是一样的,修改不会改变原来的值,而对于可变类型的浅拷贝是换了个容器装的同一批东西,对于不可变类型做了更改不会影响老容器,对于修改内部嵌套的容器会影响原容器,深拷贝就是将外面的最大容器换了一个,如果内部有嵌套,嵌套的容器也会跟着换个容器装相同的东西,对于修改不会影响原容器
2 __new__和__init__的区别
1.双下new要有返回值,而双下init不需要
2.双下new是在双下init之前执行,且双下new必须顺利执行完成,才会执行双下init

-----------
3 把一个文件夹,子文件夹下所有的folder.ini删除
4 前端有个输入框  有个按钮,输入框输入一个 服务器的地址  d://home
    把该文件夹下的所有 xx.mp4 显示在前端

posted on 2022-08-02 21:12  淦白嫖怪  阅读(71)  评论(0)    收藏  举报

导航