view demo

class ValidateCodeSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = VerifyCodeSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        mobile = serializer.validated_data["mobile"]  # 验证成功可以通过validated_data获取值

        code = generator_code()
        print(len(code))
        print(code)
        verify_code = VerifyCode(mobile=mobile, code=code)
        verify_code.save()
        return Response({"mobile": mobile}, status=status.HTTP_200_OK)

serializerDemo

class VerifyCodeSerializer(serializers.Serializer):
    mobile = serializers.CharField()

    def validate_mobile(self, mobile):
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("用户已存在")

        if not re.match(r"^1[35678]\d{9}$", mobile):
            raise serializers.ValidationError("手机号非法")

        now = datetime.datetime.now()
        onmin_ago = now - datetime.timedelta(hours=0, minutes=1, seconds=0)
        if VerifyCode.objects.filter(add_time__gt=onmin_ago):
            raise serializers.ValidationError("发送频率太高")

        return mobile

 

posted on 2019-04-05 19:54  chester·chen  阅读(743)  评论(0编辑  收藏  举报