多方式登录与手机号验证接口,腾讯云短信介绍和申请

1,204 阅读4分钟

首页中间部分样式

<div class="course">
      <el-row>
        <el-col :span="6" v-for="(o, index) in 8" :key="o" class="course_detail">
          <el-card :body-style="{ padding: '0px' }">
            <img src="https://tva1.sinaimg.cn/large/e6c9d24egy1h1g0zd133mj20l20a875i.jpg"
                 class="image">
            <div style="padding: 14px;">
              <span>推荐课程</span>
              <div class="bottom clearfix">
                <time class="time">价格:999</time>
                <el-button type="text" class="button">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <img src="https://tva1.sinaimg.cn/large/e6c9d24egy1h1g112oiclj224l0u0jxl.jpg" alt="" width="100%" height="500px">
    
    
    
    
<style scoped>
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.course_detail {
  padding: 50px;
}
</style>
    
    

多方式登录接口

登录方式有多种:
	用户名/手机号/邮箱 + 密码
	数据格式:{username:用户名/邮箱/手机号,password:123}---->post请求
需要写的接口:
	1 多方式登录 【用户名、邮箱、手机号+密码】
	2 验证码登录
    3 发送验证码
    4 校验手机号是否存在
    5 手机号注册接口

views.py

# post请求--->查询单个--->自动生成路由
# 考虑继承ViewSet,在里边编写mul_login函数,并用action装饰器装饰


from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.exceptions import ValidationError, APIException
from rest_framework.viewsets import ViewSet
from utils.response import APIResponse
from .serializer import UserLoginSerializer
from .models import UserInfo


class UserView(ViewSet, ListAPIView):
    @action(methods=['POST', ], detail=False)
    def mul_login(self, request):
        # 之前面条版,代码都在视图类里边,非常冗余,我们可以考虑把代码写在序列化类中,在里边校验登录信息,并签发token。
        ser = UserLoginSerializer(data=request.data)
        # 序列化不通过就抛异常
        ser.is_valid(raise_exception=True)  # 会依次执行:序列化类字段自己的校验规则,局部钩子,全局钩子
        username = ser.context.get('username')
        token = ser.context.get('token')
        icon = ser.context.get('icon')  
        return APIResponse(token=token, username=username, icon=icon)
		# 返回给前端,看到的样子:{code:100,msg:成功,token:adsfa,username:root,icon:http://adsfasd.png}

serializer.py

import re
from rest_framework.exceptions import ValidationError, APIException
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import UserInfo

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


# 这个序列化类,只用来做登录校验,不做序列化和反序列化
class UserLoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField()  # 坑。 这里要重写username的校验规则,不然映射过来的规则会有 unique=True。用户名重复会报错,这对登录接口来说显然不合理。

    class Meta:
        model = UserInfo
        fields = ['username', 'password']

    def _check_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        # username可能是用户名,邮箱,手机号---》使用正则判断
        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()
        try:
            # 这里不使用authenticate,因为他只针对用户名和密码,但我们的username字段可能是电话号码或者邮箱。所以我们这里把user取出,用check_password来做判断
            user.check_password(password)
            return user
        except:
            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 ValidationError(str(e))

    def validate(self, attrs):
        # 这里我们把校验用户名密码和签发token拆成两个函数,目的也是为了使代码清晰整洁,方法用_装饰,是约定俗成的用法,表示该方法不想让该类外边的对象来调用
        # 校验用户名密码
        user = self._check_user(attrs)
        # 签发token
        token = self._get_token(user)
        # 通过上下文 将user和token传给视图类
        self.context['username'] = user.username
        self.context['token'] = token
        self.context['icon'] = str(user.icon)
        return attrs

urls.py

from django.contrib import admin
from django.urls import path, re_path
from home import views
from django.views.static import serve
from django.conf import settings
from . import views

from rest_framework.routers import SimpleRouter

router = SimpleRouter()
# 127.0.0.1:8080/api/v1/userinfo/user/mul_login
router.register('user', views.UserView, 'user')

urlpatterns = [
]
urlpatterns += router.urls

手机号是否存在接口

get请求:  127.0.0.1:8080/api/v1/userinfo/user/mobile/?mobile=132222222
class UserView(ViewSet):
    @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:手机号不存在}

腾讯云短信介绍和申请

# 咱们要写发送短信接口,我们要发短信,借助于短信运营商

# 腾讯云开放平台,有很多开放的接口供咱们使用,咱们用的是短信
	-注册平台---》找到短信
    -https://console.cloud.tencent.com/smsv2
    
    
# 申请使用腾讯云短信:
	1 创建签名:使用公众号申请
    	-网站:备案:工信部备案
        -申请个人一个公众号:
        	-https://mp.weixin.qq.com/
        -等审核通过
    2 申请模板:发送短信的模板 {1}  {2} 后期用代码填上
    
    3 免费赠送1004 代码发送短信:参照文档写代码:https://cloud.tencent.com/document/product/382/13444
    	-v2 老一些
        -v3 最新

![27](E:\知识点归档\12 Luffy\imgs\27.png)

![27](E:\知识点归档\12 Luffy\imgs\28.png)

什么是api,什么是sdk

# API文档
	-之前学的接口文档的概念
    -使用api调用,比较麻烦,固定输入,接受固定的返回
    -使用postman都可以测试,携带你的认证的秘钥。
    
# SDK:Software Development Kit 软件开发工具包
	-分语言的
    -基于API,使用某个编程语言封装的包
    -例如python:pip install 包
    	-包.发短信(参数)
        
   -一般厂商都会提供各大主流语言的sdk


# 腾讯短信sdk使用步骤
    1 已开通短信服务,创建签名和模板并通过审核    # 开了
    2 如需发送国内短信,需要先 购买国内短信套餐包。 #赠送了
    3 已准备依赖环境:Python 2.7 - 3.6 版本。    #我们有
    4 已在访问管理控制台 >API密钥管理页面获取 SecretID 和 SecretKey。
        SecretID 用于标识 API 调用者的身份。
        SecretKey 用于加密签名字符串和服务器端验证签名字符串的密钥,SecretKey 需妥善保管
    5 短信的调用地址为sms.tencentcloudapi.com。