首页 > 解决方案 > Django Rest Framework Scope Throttling on 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

我试着环顾四周,但所有答案都只针对基于类的视图。不胜感激,谢谢。

标签: pythondjangodjango-rest-frameworkthrottling

解决方案


您可以通过首先创建所有自定义限制类来解决此问题。注意:只有油门在类中,但视图是函数。

class PostAnononymousRateThrottle(throttling.AnonRateThrottle):
    scope = 'post_anon'
    def allow_request(self, request, view):
        if request.method == "GET":
            return True
        return super().allow_request(request, view)

class GetAnononymousRateThrottle(throttling.AnonRateThrottle):
    scope = 'get_anon'
    def allow_request(self, request, view):
        if request.method == "POST":
            return True
        return super().allow_request(request, view)

class PostUserRateThrottle(throttling.UserRateThrottle):
    scope = 'post_user'
    def allow_request(self, request, view):
        if request.method == "GET":
            return True
        return super().allow_request(request, view)

class GetUserRateThrottle(throttling.UserRateThrottle):
    scope = 'get_user'
    def allow_request(self, request, view):
        if request.method == "POST":
            return True
        return super().allow_request(request, view)

如果您不是在寻找身份验证或方法类型,则可以选择消除这些类。

然后你需要导入这个

from rest_framework.decorators import api_view, throttle_classes

然后,您可以使用创建的所有权限的 throttle_classes 装饰器包装您的函数视图

@api_view(['GET', 'POST'])
@throttle_classes([PostAnononymousRateThrottle, GetAnononymousRateThrottle, PostUserRateThrottle, GetUserRateThrottle])
def someFunction(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    elif request.method == 'GET':
        return Response({"message": "Hello, world!"})

不要忘记在 settings.py 中提及油门速率

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'post_anon': '3/minute',
        'get_anon': '1/minute',
        'post_user': '2/minute',
        'get_user': '2/minute'
    }
}

参考:https ://medium.com/analytics-vidhya/throttling-requests-with-django-rest-framework-for-different-http-methods-3ab0461044c


推荐阅读