07前后端项目上传gitee,后端多方式登录接口,发送短信功能,发送短信封装,短信验证码接口,短信登录接口,#将视图层和序列化类进行简单的封装

发布时间 2023-06-25 22:12:03作者: 无敌大帅逼

1 前后端项目上传到gitee

# 公司里:
	-前端一个仓库---》一个团队
    -后端一个仓库---》一个团队
    
    -微服务:两三个人一个服务---》一个项目一个仓库
    
    -网上开源软件,前后端都在一起
    
    
    
# 在远端建立前端仓库
#本地代码提交到远成 仓库

2 后端多方式登录接口

# 登录注册相关功能
	- 1 校验手机号是否存在(已经完成)
    - 2 多方式登录接口(手机号,邮箱,用户名都可以登录成功)
    - 3 发送短信接口(腾讯云短信)
    - 4 短信登录接口
    - 5 短信注册接口

2.1效验手机号是否登录

视图层

image

2.2 多方式登录接口

视图类

class UserView(GenericViewSet):
    serializer_class = LoginUserSerializer
    # 多方式登录接口--->要不要序列化类---》要用序列化类---》继承的视图类基类---》
    # post请求---》前端携带的数据 {username:xxx,password:123}--->post请求
    @action(methods=['POST'], detail=False)
    def mul_login(self, request, *args, **kwargs):
        # 校验逻辑要写在序列化类中
        ser = self.get_serializer(data=request.data)
        # 只要执行它,就会执行 字段自己的校验规则,局部钩子,全局钩子(全局钩子中写验证逻辑,生成token的逻辑)
        ser.is_valid(raise_exception=True)  # 如果校验失败,异常会往外跑
        username = ser.context.get('username')
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        return APIResponse(username=username, token=token,icon=icon)

序列化类

from .models import User
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django.db.models import Q
from rest_framework.exceptions import APIException, ValidationError
from django.conf import settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class LoginUserSerializer(serializers.ModelSerializer):
    # 字段自己的规则,会走唯一性叫校验---》就过不了----》必须要重写该字段
    username = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ['username', 'password']  # 只做数据校验---》写校验的字段


    def _get_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        # user=User.objects.filter(username=username || mobile=username || email=username)
        user = User.objects.filter(Q(username=username) | Q(mobile=username) | Q(email=username)).first()
        if user and user.check_password(password):
            # 说明用户名存在,密码再校验
            return user
        else:
            raise APIException('用户名或密码错误')


    def _get_token(self, user):
        # jwt的签发
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token


    def validate(self, attrs):
        # 验证用户名密码逻辑----》签发token逻辑
        # username字段可能是 用户  ,手机号,邮箱---》正则匹配---》换一种方式 使用Q查询
        user = self._get_user(attrs)
        # 签发token
        token = self._get_token(user)
        '''
        将数据存入上下文context里面,如果存入self.username = username里面容易产生脏数据
        '''
        self.context['username'] = user.username
        self.context['icon'] = settings.BACKEND_URL + user.icon.url
        self.context['token'] = token

        return attrs

3 发送短信功能

#  什么是API,什么是SDK
	-API:api接口----》发送http请求,到某些接口,携带需要携带的数据,就能完成某些操作
    	-python发送http请求,目前不会=====》requests模块
    -sdk:集成开发工具包,跟语言有关系---》官方提供的,使用某种语言对api接口做了封装---》使用难度很低
    
    -有sdk优先用sdk---》正统用法,下载,导入,类实例化---》调用类的某个方法完成功能
    
    
# 测试发送短信
	-1 安装pip install --upgrade tencentcloud-sdk-python
    -2 复制代码修改:https://cloud.tencent.com/document/product/382/43196

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:
    # 必要步骤:
    # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
    cred = credential.Credential("", "")

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略)
    # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口")
    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

    # 实例化要请求产品(以sms为例)的client对象
    # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
    client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

    # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
    # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
    # 属性可能是基本类型,也可能引用了另一个数据结构
    # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
    req = models.SendSmsRequest()
    # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
    req.SmsSdkAppId = "1400832755"
    # 短信签名内容: 使用 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 = "1842867"
    # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
    req.TemplateParamSet = ["8888",'5']
    # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
    # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
    req.PhoneNumberSet = ["+8618576031435"]
    # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
    req.SessionContext = ""
    # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
    req.ExtendCode = ""
    # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
    req.SenderId = ""

    resp = client.SendSms(req)

    # 输出json格式的字符串回包
    print(resp.to_json_string(indent=2))
except TencentCloudSDKException as err:
    print(err)

4 发送短信封装

# 第三方的发送短信,封装成包
	-不仅仅在django中使用,后期在其它任意的项目中都可以使用
    
# 创建一个包
send_tx_sms
    __init__.py
    settings.py
    sms.py
    
#####  __init__.py#########
from .sms import get_code,send_sms_by_mobile

##### settings.py#######

SECRET_ID=''
SECRET_KEY=''
SMS_SDK_APP_ID = '1400832755'
SIGN_NAME='寻觅烟雨公众号'
TEMPLATE_ID='1842867'

######## sms.py######## ######## ######## ######## ######## 

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 random


# 生成验证码
def get_code(num=4):
    code = ''
    for i in range(num):
        res = random.randint(0, 9)
        code += str(res)  # 强类型,字符串不能加数字

    return code

def send_sms_by_mobile(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.SMS_SDK_APP_ID
        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, '5']
        req.PhoneNumberSet = ["+86" + mobile]
        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        res_dict = resp._serialize(allow_none=True)
        if res_dict['SendStatusSet'][0]['Code'] == "Ok":
            return True
        else:
            return False

    except TencentCloudSDKException as err:
        print(err)  # 记录日志
        return False

5 短信验证码接口

    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        # 前端需要把要发送的手机号传入 在地址栏中
        mobile = request.query_params.get('mobile', None)
        code = get_code()  # 把code存起来,放到缓存中
		
        cache.set('send_sms_code_%s' % mobile, code)
        #不同的人存不同的key
		
        if mobile and send_sms_by_mobile(mobile, code):
            return APIResponse(msg='发送成功')
        raise APIException('发送短信出错')
        
        
     
    
 # 咱们的短信验证码不安全
	-1 频率:限制ip,限制手机号
    	-代理池解决
    -2  携带一个特定加密串(两端token串)--->post请求
    	-data:base64编码的串.base64编码串
        -{phone:11111,ctime:323453422}.签名
        	-判断超时
            -验证签名

6 短信登录接口

6.1 视图类

    def get_serializer_class(self):
        if self.action == 'sms_login':
            return LoginUserSMSSerializer
        else:
            # return super().get_serializer_class()
            return self.serializer_class

    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        # 前端传入的格式  {mobile:12344,code:8888}
        return self._common_login(request, *args, **kwargs)

    def _common_login(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        # 只要执行它,就会执行 字段自己的校验规则,局部钩子,全局钩子(全局钩子中写验证逻辑,生成token的逻辑)
        ser.is_valid(raise_exception=True)  # 如果校验失败,异常会往外跑
        username = ser.context.get('username')
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        return APIResponse(username=username, token=token, icon=icon)

6.2 序列化类

from django.core.cache import cache


class CommonLoginSerializer():
    def _get_user(self, attrs):
        raise APIException('你必须重写')

    def _get_token(self, user):
        # jwt的签发
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

    def validate(self, attrs):
        # 验证用户名密码逻辑----》签发token逻辑
        # username字段可能是 用户  ,手机号,邮箱---》正则匹配---》换一种方式 使用Q查询
        user = self._get_user(attrs)
        # 签发token
        token = self._get_token(user)
        # 把用户,token放在 序列化类的context中【上下文】
        self.username = user.username
        self.context['username'] = user.username
        self.context['icon'] = settings.BACKEND_URL + user.icon.url
        self.context['token'] = token

        return attrs




class LoginUserSMSSerializer(CommonLoginSerializer, serializers.Serializer):
    code = serializers.CharField(max_length=4)
    mobile = serializers.CharField()

    def _get_user(self, attrs):
        # attrs 中又手机号和验证码
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        # 验证验证码是否正确
        old_code = cache.get('send_sms_code_%s' % mobile)
        if code == old_code:
            # 验证码正确,查user
            user = User.objects.filter(mobile=mobile).first()
            if user:
                return user
            else:
                raise APIException('手机号没注册')
        else:
            raise APIException('验证码错误')

将视图层和序列化类进行简单的封装

视图层

from django.shortcuts import render
from django.core.cache import cache  #加入缓存

from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.viewsets import GenericViewSet

from .models import User
from luffy_api.libs.send_tx_sms import get_code,send_sms_by_mobile
from luffy_api.utils.common_response import APIResponse
from .serializer import LoginUserSerializer,LoginUserSMSSerializer



class UserView(GenericViewSet):
    serializer_class = LoginUserSerializer
    '''
    验证手机号是否存在接口---》get请求---》跟数据库有关系,但不需要序列化----》自动生成路由
    '''
    @action(methods=['GET'],detail=False)
    def check_mobile(self,request,*args,**kwargs):
        try:
            mobile = request.query_params.get('mobile',None)
            User.objects.get(mobile=mobile)  # 有且只有一条才不报错,如果没有或多余一条,就报错
            return APIResponse(msg='手机号存在')
        except Exception as e:
            raise APIException('手机号不存在')

    '''
    公共的
    '''
    def _common_login(self,request,*args,**kwargs):
        ser = self.get_serializer(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(username=username,token=token,icon=icon)

   #重写get_serializer_class方法
    def get_serializer_class(self):
        if self.action == 'sms_login':
            return LoginUserSMSSerializer  #serializer_class = LoginUserSMSSerializer
        return self.serializer_class



    '''
    多方式登录接口--->要不要序列化类---》要用序列化类---》继承的视图类基类---》post请求---》前端携带的数据 {username:xxx,password:123}--->post请求
    '''
    @action(methods=['POST'], detail=False)
    def mul_login(self,request,*args,**kwargs):
        return self._common_login(request,*args,**kwargs)


    '''
    发送短信获得验证码
    '''
    @action(methods=['GET'], detail=False)
    def send_sms(self,request,*args,**kwargs):
        mobile = request.query_params.get('mobile',None) #获取请求头里面的手机号
        code = get_code() #获取随机验证码
        cache.set('send_sms_code_%s' % mobile, code)#不同的人存不同的key,通过后面格式化的手机号作区分
        if mobile and send_sms_by_mobile(mobile,code):#短信发送成功则返回ture
            return APIResponse(msg='发送成功')
        raise APIException('发送短信错误')

    '''
    手机验证码登录
    '''
    @action(methods=['POST'], detail=False)
    def sms_login(self,request,*args,**kwargs):
	#执行的是LoginUserSMSSerializer序列化类
        return self._common_login(request,*args,**kwargs)

序列化类

from django.db.models import Q
from .models import User
from django.conf import settings
from django.core.cache import cache

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from rest_framework.exceptions import APIException,ValidationError
from rest_framework_jwt.views import obtain_jwt_token


jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class CommonLoginSerializer():
    def _get_user(self,attrs):  #假如后面继承这个方法的父类没有重写该方法获取user则报错
        raise APIException('你必须重写')

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

    def validate(self,attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        '''
        将数据存入上下文context里面,如果存入self.username = username里面容易产生脏数据
        '''
        self.context['username'] = user.username
        self.context['icon'] = settings.BACKEND_URL + user.icon.url  #BACKEND_URL = 'http://127.0.0.1'
        self.context['token'] = token
        return attrs


'''
效验姓名/邮箱/手机号    密码登录
'''
#该序列化类只做效验不做序列化和返序列化
class LoginUserSerializer(CommonLoginSerializer, serializers.ModelSerializer):
    username = serializers.CharField(required=True)
    class Meta:
        model = User
        fields = ['username','password']

    def _get_user(self,attrs): #attr = {'username':'xxxx','password':'xxxx'}
        username = attrs.get('username')
        password = attrs.get('password')
        user = User.objects.filter(Q(username=username)| Q(mobile = username)|Q(email = username)).first()
        if user and user.check_password(password):#直接通过auth模块效验密码是否正确
            return  user
        raise APIException('用户名或者密码错误')


'''
效验验证码登录  
'''
class LoginUserSMSSerializer(CommonLoginSerializer,serializers.Serializer):
    code = serializers.CharField(max_length=4)
    mobile = serializers.CharField()

    def _get_user(self,attrs):
        #attrs里面是前端传入的{'mobile':'17354368484','code':'2137'}
        mobile = attrs.get('mobile')
        code = attrs.get('code') #你要输入的验证码

        old_code = cache.get('send_sms_code_%s'%mobile) #手机上得到的验证码  cache = {'send_sms_code_xxx':'验证码'}
        if code == old_code: #如果输入的验证码和得到的验证码一样时
            user = User.objects.filter(mobile=mobile).first()
            if user:
                return user
            else:
                raise APIException('手机号没有注册')
        else:
            raise APIException('验证码错误')