• drf权限组件


    from app01 import models
    from rest_framework import exceptions
    from rest_framework.authentication import BaseAuthentication
    
    
    # 用drf的认证,写一个类
    class LoginAuth(BaseAuthentication):
        # 函数名一定要叫authenticate,接收必须两个参数,第二个参数是request对象
        def authenticate(self, request):
            # 从request对象中取出token(也可以从其它地方取)
            token = request.query_params.get('token')
            # 去数据库过滤,查询
            ret = models.UserToken.objects.filter(token=token).first()
            if ret:
                # 能查到,说明认证通过,返回空
                # ret.user就是当前登录用户对象
                return ret.user, ret
            # 如果查不到,抛异常
            raise exceptions.APIException('您认证失败')
    
    from rest_framework.permissions import BasePermission
    class UserPermission(BasePermission):
        # message是出错显示的中文
        message='您没有权限查看'
        def has_permission(self, request, view):
            user_type = request.user.user_type
            # 取出用户类型对应的文字
            # 固定用法:get_字段名字_display()
            user_type_name = request.user.get_user_type_display()
            print(user_type_name)
            if user_type == 2:
                return True
            else:
                return False
    from rest_framework import serializers
    from app01 import models
    
    
    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Book
            fields='__all__'
    
    class AuthorSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Author
            fields='__all__'
    
    
    class UserSer(serializers.ModelSerializer):
        class Meta:
            model = models.UserInfo
            fields='__all__'
    
        # user_type=serializers.CharField(source='get_user_type_display')
        user_type=serializers.SerializerMethodField()
        def get_user_type(self,obj):
            return obj.get_user_type_display()
  • 相关阅读:
    效率较高的排序算法
    django进阶
    django报错TypeError: __init__() missing 1 required positional argument: 'on_delete'
    DjangoORM基本增删改查
    C++中关键字static的作用
    Sqlite的安装和使用 (windows,C#)
    sqlserver查询时对于字符串类型的数据是否区分大小写
    C#自己无聊写的2048小游戏
    C#自己无聊写的俄罗斯方块游戏
    C#实现非枚举类型的在属性控件中可下拉选择(二)
  • 原文地址:https://www.cnblogs.com/xuqidong/p/13506063.html
Copyright © 2020-2023  润新知