【问题标题】:Django REST POST and GET different throttle scopesDjango REST POST 和 GET 不同的油门范围
【发布时间】:2019-05-30 03:53:52
【问题描述】:

我有 django-rest 视图类 Photo 和 get 和 post 方法,我想让用户在一小时内上传一张 POST 照片,并在一分钟内完成 1000 个 GET 照片请求。默认情况下,我可以为所有APIView(获取和发布)设置throttle_scope

如何执行?创建两个不同范围的不同视图?

谢谢。

【问题讨论】:

    标签: django-rest-framework


    【解决方案1】:

    解决方案一:

    这有点棘手,我没有测试它。

    覆盖 APIView 中的 get_throttles 方法。

    class PhotoView(APIView):
        throttle_scope = 'default_scope'
    
        def get_throttles(self):
            if self.request.method.lower() == 'get':
                self.throttle_scope = 'get_scope'
            elif self.request.method.lower() == 'post':
                self.throttle_scope = 'post_scope'
    
            return super(PhotoView, self).get_throttles()
    

    解决方案 2

    您应该为不同的scope_attr 定义自己的ScopedRateThrottle 类。

    class FooScopedRateThrottle(ScopedRateThrottle):
        scope_attr = 'foo_throttle_scope'
    
    class BarScopedRateThrottle(ScopedRateThrottle):
        scope_attr = 'bar_throttle_scope'
    
    class PhotoView(APIView):
        foo_throttle_scope = 'scope_get'
        bar_throttle_scope = 'scope_post'
    
        def get_throttles(self):
            ret = []
            if self.request.method.lower() == 'get':
                return [FooScopedRateThrottle(), ]
            elif self.request.method.lower() == 'post':
                return [BarScopedRateThrottle(), ]
            else:
                return super(PhotoView, self).get_throttles()
    

    仅供参考。相关源码:get_throttlesScopedRateThrottle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多