加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

django-rest-framework – Django REST POST和GET不同的节流范围

发布时间:2020-12-20 11:50:27 所属栏目:Python 来源:网络整理
导读:我有 django-rest视图类带有get和post方法的照片,我希望允许用户在一分钟内制作一张POST照片上传一小时和1000张GET照片请求.默认情况下,我可以为所有APIView设置throttle_scope(get和post). 怎么做?使用不同的范围创建两个不同的视图? 谢谢. 解决方法 解决
我有 django-rest视图类带有get和post方法的照片,我希望允许用户在一分钟内制作一张POST照片上传一小时和1000张GET照片请求.默认情况下,我可以为所有APIView设置throttle_scope(get和post).

怎么做?使用不同的范围创建两个不同的视图?

谢谢.

解决方法

解决方案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_throttles和ScopedRateThrottle

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读