django 石墨烯速率限制(节流)

django graphene rate limit (throttling)

我正在 Django RF 上构建 REST Api。我需要设置来自 IP 的请求限制。对于 views.py 中的常规 Api 端点,只需添加以下设置即可轻松做到这一点

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}

但我也有一个用于 graphql 的 Graphene django api。

如何为该视图设置速率限制?我试过 django-ratelimit,但它对我不起作用。

问题已通过将 GraphQL 视图自定义为以下内容得到解决:

from graphene_django.views import GraphQLView


class CustomGraphQL(GraphQLView):
    def parse_body(self, request):
        if isinstance(request, Request):
            return request.data
        return super().parse_body(request)

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = authentication_classes((TokenAuthentication,))(view)
        view = throttle_classes((AnonRateThrottle, AnonMinutesThrottle,
                                 AnonSecondsThrottle, UserRateThrottle))(view)
        view = api_view(['GET', 'POST'])(view)
        return view