第五天

login联调

vuex => login.vue->actions.js->mutations->存入state
django自带的登录只验证username,需要验证手机,所以重载验证函数
->自定义用户验证 django默认用户验证类
->django.contrib.auth.backends.ModelBackend
在setting中重新设置
AUTHENTICATION_BACKENDS =['自定义的认证类']
然后自己重写认证类

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.contrib.auth import get_user_model

User = get_user_model()
class CustomBackend(ModelBackend):  # 继承自默认配置的类
    """
    自定义用户验证类
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

jwt的相关配置 -> (在setting中)

import datetime
JWT_AUTH = {
    # 配置详情参见官方文档:https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/docs/index.md
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',  # token的名字
}

云片网发送手机短信

import requests #什么时候安装的

# -*- coding: utf-8 -*-
import requests

class YunPian(object):

    def __init__(self, api_key):
        self.api_key = api_key
        self.single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json'

    def send_sms(self, code, mobile):
        params = {
            "apikey": self.api_key,
            "mobile": mobile,
            "text": "【历历万乡】您的验证码是{code}。如非本人操作,请忽略本短信".format(code=code)
        }

        response = requests.post(self.single_send_url, data=params)
        import json
        re_dict = json.loads(response.text)
        print(re_dict)

if __name__ == '__main__':
    yun_pian = YunPian("042cdd2e94d8649d2e61d2350da61cc1")
    yun_pian.send_sms("111111", "15111171986")

如果测试失败,将本地ip写入云片后台的白名单
单文件单纯测试短信api,尚未应用。
改掉写单引号的习惯,改为双引号。谢谢

class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):  # 函数的名称必须是validate+字段名
        # 手机是否注册
        if User.objects.filter(mobile=mobile):
            raise serializers.ValidationError("用户已经存在")

        # 验证手机号码
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码非法")

        # 验证上一次发送时间
        one_minutes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        if VerifyCode.objects.filter(add_time__gt=one_minutes_ago, mobile=mobile).count():
            raise serializers.ValidationError("距离上一次发送未超过60s")

        return mobile

非常重要:def validate_mobile(self, mobile): # 函数的名称必须是validate+字段名,在serializer类下该函数是自运行函数
django的错误用一个list返回在字段的属性里面
drf官方文档中关于serializer的fields中的core arguments
其中有个参数是write_only: code设置这个参数,防止返回时序列化报错->返回时该属性已经被删除。

class UserRegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField(write_only=True)
-------------------------------------------------------------------------------------------
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
用户密码设置方法1(serializer中)
    def create(self, validated_data):
        user = super(UserRegisterSerializer, self).create(validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user

**新写信号量文件的方式 -> appsconfig中重载ready函数**
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.contrib.auth import get_user_model

User = get_user_model()
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        password = instance.password
        instance.set_password(password)
        instance.save()
        # Token.objects.create(user=instance) 采用了jwt,此种方式删除
以下函数必须重载,否则返回的对象为空,导致bug
def perform_create(self, serializer):  # 此处重载将user返回
    return serializer.save()

需要多看前端源码

你可能感兴趣的:(第五天)