• python项目_实现注册功能


    1.完成路由接口的填写

    2.完成视图代码的编写

    from rest_framework.generics import CreateAPIView
    from .models import User
    from .serializers import UserModelSerializer
    class UserAPIView(CreateAPIView):
        """用户注册"""
        queryset = User.objects.all()
        serializer_class = UserModelSerializer

    3.完成序列化器代码的编写

    from rest_framework import serializers
    from .models import User
    import re
    
    class UserModelSerializer(serializers.ModelSerializer):
        """用户序列化器"""
        sms = serializers.CharField(write_only=True, max_length=6, min_length=4, help_text="短信验证码")
        token = serializers.CharField(read_only=True, min_length=1, help_text="jwt")
        class Meta:
            model = User
            fields = ["id","username","token","password","mobile","sms"]
            # 字段的额外声明
            extra_kwargs = {
                "id":{ "read_only": True, },
                "username":{ "read_only": True, },
                "password":{ "write_only": True, "min_length": 6, },
                "mobile":{ "write_only": True, "min_length": 11 },
            }
    
        def validate(self, attrs):
            mobile = attrs.get("mobile")
            ret = re.match(r"1[3-9]d{9}$",mobile)
            if not ret:
                raise serializers.ValidationError("对不起,手机格式错误!")
    
            try:
                User.objects.get(mobile=mobile)
                raise serializers.ValidationError("对不起,当前手机号已经被注册!")
            except User.DoesNotExist:
                pass
    
            # todo 验证短信是否正确
    
            return attrs     ##返回值的作用是???
    
        def create(self, validated_data):
            mobile = validated_data.get("mobile")
            password = validated_data.get("password")
            username=mobile
            try:
                user = User.objects.create_user(username=username, password=password,mobile=mobile)
            except:
                raise serializers.ValidationError("创建用户失败!")
    
            # 手动生成jwt
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            user.token = jwt_encode_handler(payload)
    
            return user
  • 相关阅读:
    iOS iPad开发之Modal
    iOS SVN终端指令
    iOS iPad开发之UIPopoverController的使用
    iOS Xcode6和Xcode5的区别?
    算法 查找算法--二分查找
    算法 排序算法--快速排序
    算法 排序算法--选择排序
    XCode签名证书死活不能选
    IOS7 适配时导航栏变黑
    Xcode Provisioning 路径
  • 原文地址:https://www.cnblogs.com/jalen-123/p/13168013.html
Copyright © 2020-2023  润新知