zoukankan      html  css  js  c++  java
  • drf 之 五 权限源码分析 模型层choice字段使用(重点) 自定义频率类(分析,了解) 内置频率类使用 内置,第三方过滤功能 排序功能

    权限源码分析  模型层choice字段使用(重点)  自定义频率类(分析,了解)  内置频率类使用  内置,第三方过滤功能 排序功能

    一、权限源码分析

    源码分析
        APIView的dispatch-->APIView的initial--》APIView的check_permission(request)
      for permission in self.get_permissions(): #将权限类对象放到列表中
        if not permission.has_permission(request,self):
          self.permission_denied(
            request,
            message=getattr(permission,'message',None),
            code=getattr(permission,'code',None))
          
    错误信息的中文显示
      在权限类中加一个message = 字符串

    二、模型层choice字段的使用(重点)

    1、模型表:Student表,写接口应该选择继承那个视图类
    2、推荐使用自动生成路由的方式(继承ViewSetMixin及他的子类)
    3、choice的使用
        在模型类中使用
            sex=models.SmallIntegerField(choices=((1,''),(2,''),(3,'未知')),default=1)
    在视图类中,在序列化类中
    get_字段名_display()的方法,该方法获得choice字段对应的数据
    class StudentSerializer(serializers.ModelSerializer):
    sex=serializers.CharField(source='get_sex_display') #实现原理:在StudentSerializer隐藏了一个get_sex_display函数,会根据choice的的值返回男和女,所以只需要配置即可。
    class Meta:
    model = Student
    fields='__all__'

    三、自定义频率类(分析,了解)

    1 限制某个人,某个ip的访问频次
    2 自定义频率类及使用
    from rest_framwork.thorttling import BaseThorttle
    class MyThrottle(BaseThrottle):
      VISIT_RECORD = {} #存用户访问信息的大典
      def __init__(self):
        self.history = None
      def allow_request(self,request,view):
        根据ip进行频率限制,每分钟只能访问三次
        限制ip的逻辑
        1.取出访问者的ip
        2.判断当前ip在不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
        3.判断循环当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表
          中只有60s以内的访问时间
        4.判断,当列表小于三,说明一分钟以内访问的次数不足三次,把当前时间插入到列表的第一个位置,返回True顺了通过
        5.当大于等于三时,说明一分钟内访问超过三次,返回False验证失败

        
         ip = request.META.get('REMOTE_ADDR')
      import time
      ctime = time.time()
        判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问
      if ip not in self.VISIT_RECORD:
      self.VISIT_RECORD[ip] = [ctime,]
      return True

      self.history = self.VISIT_RECORD.get(ip)
        循环判断当前ip的列表,有值,并且当时间减去列表最后一个时间大于60s,把这种数据pop掉,这样列表中只有
        60s以内访问的时间
      while self.history and ctime-self.history[-1] > 60:
        self.history.pop()
       
        判断当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
        当大于等于三,说明一分钟内访问超过三次,返回False验证失败
    if len(self.history) < 3:
        self.history.insert(0,ctime)
        return True
      else:
        return False


    def wait(self):
      #还剩多长时间能访问
    import time
    ctime = time.time()
    return 60 - (ctime-self.history[-1])

    3 使用:
      只有局部使用和全局使用

    四、内置频率类使用

    1 使用
    局部使用
        throttle_classes = [auth.MyThrottle,]
    全局使用
        REST_FRAMWORK = {
        'DEFAULT_THROTTLE_CLASSES':['app01.auth.MyThrottle',],}
    2 内置频率类
        BaseThrottle:基类
        AnonRateThrottle:限制匿名用户的访问次数
        SimpleRateThrottle:自定义扩写他
        ScopeRateThrottle:
        UserRateThrottle:限制登录用户访问次数
    3 扩展内置频率类(重点记住)
    写一个类,继承SimpleRateThrottle
      class MySimpleThrottle(SimpleRateThrottle):
        scope = 'xxx'
        def get_cache_key(self,request,view):
          #以ip为限制
          return self.get_ident(request)
      setting.py中配置
      REST——FRAMEWORK =
    {

        'DEFAULT_THROTTLE_RATES' : {
        'xxx':'10/m'# key跟scope对应,value是一个时间
        }
          }
    局部使用和全局使用

    4 源码分析

    继承SimpleRateThrottle-->allow_request(同上的代码)

    5 其他内置频率类

    限制未登录用户的频率(AnonTateThrottle) (根据ip限制)

      使用:

        局部使用,全局使用
          setting.py中配置
          'DEFAULT_THROTTLE_RATES' : {
          'anon':'1/m'
                  }
    限制登录用户访问次数UserRateThrottle(根据用户id限制)
    使用:
    局部使用,全局使用
       setting.py中配置
          'DEFAULT_THROTTLE_RATES' : {
          'user':'1/m'  
              }
    ScopedRateThrottle(有兴趣看一下,没有就不看了)

        





    五、内置,第三方过滤功能(次重点)

    1 过滤:筛选查询结果
    2 内置筛选的使用
      在视图类中配置
        filter_backends = [SearchFilter,]
        search_fields = ('name') #表模型中的字段
      查询的时候
        http://127.0.0.1:8000/students/?search=e

    3 第三方扩展的过滤功能
    -pip3 install django-filter :最新版本(2.4.0)要跟django2.2以上搭配

    -在视图类中配置
    filter_backends =[DjangoFilterBackend,]
    filter_fields=['name','age']
    -查询的时候
    http://127.0.0.1:8000/students/?name=lqz&age=18


      

    六、在视图类中配置

      filter_backends = [OrderingFilter,]

      ordering_fields = ['id','age']

    查询的时候

      http://127.0.0.1:8000/students/?ordering=-age

    #过滤后在排序

    在视图类中配置

      filter_backends = [OrderingFilter,DjangoFIlterBackend]

      ordering_fields = ('id','age')

      filter_fields = ['name','age']

    查询的时候

      http://127.0.0.1:8000/students/?name=lqz&age=19&ordering=-age,-id

  • 相关阅读:
    致命错误 RC1004: 文件查找结束时有无法预知的错误(vc++)
    demo713总结
    图标,鼠标,字符串,音频..
    不同的色深条件(8、16、24、32),像素绘制方式
    SQL 保留两位小数的实现方式
    MVC4的REmote缺陷
    MVC4安装过程
    mongodb 的几种驱动
    iis7 web配置问题及解决办法
    Fast Binary File Reading with C#
  • 原文地址:https://www.cnblogs.com/ltyc/p/13964039.html
Copyright © 2011-2022 走看看