Django Rest Framework 基于函数视图的范围限制

Oma*_*yed 0 python django throttling django-rest-framework

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

例如

@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
Run Code Online (Sandbox Code Playgroud)

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

小智 7

您可以通过首先创建所有自定义限制类来解决此问题。注意:只有节流阀位于类中,而视图是函数。

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)
Run Code Online (Sandbox Code Playgroud)

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

然后你需要导入这个

from rest_framework.decorators import api_view, throttle_classes
Run Code Online (Sandbox Code Playgroud)

然后你可以用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!"})
Run Code Online (Sandbox Code Playgroud)

不要忘记在settings.py中提及节流速率

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'post_anon': '3/minute',
        'get_anon': '1/minute',
        'post_user': '2/minute',
        'get_user': '2/minute'
    }
}
Run Code Online (Sandbox Code Playgroud)

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