【发布时间】:2019-05-30 03:53:52
【问题描述】:
我有 django-rest 视图类 Photo 和 get 和 post 方法,我想让用户在一小时内上传一张 POST 照片,并在一分钟内完成 1000 个 GET 照片请求。默认情况下,我可以为所有APIView(获取和发布)设置throttle_scope。
如何执行?创建两个不同范围的不同视图?
谢谢。
【问题讨论】:
我有 django-rest 视图类 Photo 和 get 和 post 方法,我想让用户在一小时内上传一张 POST 照片,并在一分钟内完成 1000 个 GET 照片请求。默认情况下,我可以为所有APIView(获取和发布)设置throttle_scope。
如何执行?创建两个不同范围的不同视图?
谢谢。
【问题讨论】:
这有点棘手,我没有测试它。
覆盖 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()
您应该为不同的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_throttles和ScopedRateThrottle
【讨论】: