介绍
用户注册API的主要流程:1.前端用户提交用户名,密码 2. 序列化器校验用户名,密码是否合法。3.存入数据库。4.签发token
创建序列化器
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from userauth.models import User
from systemauth.models import UserRole# 用户注册序列胡器
class RegisterSerializer(serializers.Serializer):"""注册用户信息序列化校验"""username = serializers.CharField()password = serializers.CharField()def validate(self, attrs):username = attrs.get('username')password = attrs.get('password')if User.objects.filter(username=username).exists():raise serializers.ValidationError('用户名已被占用')print(password)if not password or len(password) < 6:raise serializers.ValidationError("密码不符合要求,请使用6位以上密码")if attrs.get("is_vip"):attrs['is_vip'] = Falseattrs['is_active'] = True# 将用户信息保存到数据库中user = User.objects.create(**attrs)# 为其设置角色为普通用户UserRole.objects.create(**{'user_id': user.id, 'role_id': 2})if user:# 签发token'签发token'refresh = TokenObtainPairSerializer.get_token(user)data = {'code': 100,'message': '登录成功','username': user.username,'refresh': str(refresh),'access': str(refresh.access_token),}return dataelse:raise serializers.ValidationError('用户注册失败')
view视图
from userauth.serializers import RegisterSerializer
from rest_framework.generics import GenericAPIView
class UserRegisterView(GenericAPIView):# 注册接口,局部禁用用户验证和权限authentication_classes = ()permission_classes = ()serializer_class = RegisterSerializerdef post(self, request, *args, **kwargs):res = self.get_serializer(data=request.data)res.is_valid(raise_exception=True)data = res.validated_datareturn Response({'msg': data})
路由
将路由加入验证中间件白名单
测试接口