• 动态设置serializer和permission获取用户信息


    一、用户详情的序列化

    users/serializers.py

    class UserDetailSerializer(serializers.ModelSerializer):
        """
        用户详情
        """
        class Meta:
            model = User
            fields = ['name', 'birthday', 'sex', 'phone', 'email']

    二、users/views.py

    class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        """
        create:
            创建用户
        retrieve:
            用户详情
        """
        serializer_class = UserRegSerializer
        queryset = User.objects.all()
        fields = ['username', 'password', 'phone']
    
        def create(self, request, *args, **kwargs):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            user = self.perform_create(serializer)
            re_dict = serializer.data
            payload = jwt_payload_handler(user)
            re_dict["token"] = jwt_encode_handler(payload)
            re_dict["name"] = user.name if user.name else user.username
    
            headers = self.get_success_headers(serializer.data)
            return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
    
        def perform_create(self, serializer):
            return serializer.save()
    
        def get_permissions(self):
            """
            动态权限配置
            :return: 空列表/IsAuthenticated
            """
            if self.action == 'retrieve':
                return [IsAuthenticated()]
            return []
    
        def get_serializer_class(self):
            """
            动态选择序列化的方式
            :return: 序列化对象
            """
            if self.action == 'create':
                return UserRegSerializer
            return UserDetailSerializer
    
        def get_object(self):
            """
            获取具体的那个用户
            :return: 用户
            """
            return self.request.user

    现在就可以从数据库获取用户的信息了

  • 相关阅读:
    vmware Unable to open kernel device "\.Globalvmx86": The system cannot find the file 的解决方法
    nc和telnet配合使用
    linux下批量替换文件内容
    Linux动态库的导出控制
    goang Receiver & interface
    Go与C语言的互操作 cgo
    Go fsm
    Git多账号登陆
    mysql 安装与配置、使用
    Reverse Integer
  • 原文地址:https://www.cnblogs.com/mxsf/p/10683628.html
Copyright © 2020-2023  润新知