zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    SP笔记:交叉实现七行并成一行
    HTML tag 学习
    操作哈希表
    Efficient bipedal robots based on passivedynamic walkers
    Pushing People Around
    ZEROMOMENT PONTTHIRTY FIVE YEARS OF ITS LIFE

    Active Learning for RealTime Motion Controllers
    Accelerometerbased User Interfaces for the Control of a Physically Simulated Character
    Dynamic Response for Motion Capture Animation
  • 原文地址:https://www.cnblogs.com/xuqidong/p/13506063.html
Copyright © 2011-2022 走看看