基于函数的视图上的Django Rest Framework范围限制 [英] Django Rest Framework Scope Throttling on function based view

查看:85
本文介绍了基于函数的视图上的Django Rest Framework范围限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想问是否有人知道如何在基于函数的视图中为不同的请求方法设置不同的限制范围.

Wanted to ask if someone knows a way or a workaround to how to set different throttle scopes for different request methods in a function-based view.

例如

@api_view(['GET', 'POST'])
def someFunction(request):
    if request.method == 'GET':
          # set scope for get requests
    elif request.method == 'POST':
          # set scope for post requests

我尝试环顾四周,但所有答案仅适用于基于类的视图.非常感谢您的帮助.

I tried looking around, but all answers are for class-based views only. Would appreciate the help, thanks.

推荐答案

我终于找到了基于函数的视图的解决方法.这是我的实现方式.

I finally found out a workaround for function based views. Here is how I implemented it.

如先前答案中所述,我们需要根据需要扩展UserRateThrottle类或AnonRateThrottle类.

As it was explained in previous answers, we need to extend the UserRateThrottle class or AnonRateThrottle class depending on our need.

就我而言,我对限制用户的请求更感兴趣.

For my case, I was more interested in throttling requests from users.

from rest_framework.throttling import UserRateThrottle

class CustomThrottle(UserRateThrottle):
     scope = 'my_custom_scope'
     def allow_request(self, request, view):
         if request.method == 'GET':
            self.scope = 'get_scope'
            self.rate = '2/hour'
            return True
         return super().allow_request(request, view)

在设置中:

'DEFAULT_THROTTLE_RATES': {
        'my_custom_scope': '3/day'
}

默认情况下,此类将根据设置文件中设置的速率来限制POST请求.我在这里添加的内容是在请求方法为GET的情况下更改范围和费率.如果没有这种更改,由于DRF Throttler使用的默认缓存,可能会出现一些问题.我们需要在CustomThrottle类本身内部设置速率和范围,否则与POST方法关联的范围将同时应用于GET和POST.

By default, this class will throttle POST requests based on the rate set in the settings file. The thing I added here is altering the scope and rate in case the request method was GET. Without this alteration, some problems may occur because of the default caching used by DRF Throttlers. We need to set the rate and scope inside the CustomThrottle class itself or else the scope affiliated with POST method will be applied on both GET and POST.

最后,我们在基于函数的视图中添加装饰器.

Finally, we add the decorator on our function-based view.

from rest_framework import api_view, throttle_classes
import CustomThrottle

@api_view(['GET', 'POST'])
@throttle_classes([CustomThrottle])
def someFunction(request):
    if request.method == 'GET':
          # set scope for get requests
    elif request.method == 'POST':
          # set scope for post requests

就这样:D

这篇关于基于函数的视图上的Django Rest Framework范围限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆