Two ways :
serializers.py
from rest_framework.throttling import AnonRateThrottle
class PostSearchAnonRateThrottle(AnonRateThrottle):
THROTTLE_RATES = {"anon": "6/min"}
views.py
class User_relationship(GenericAPIView, mixins.ListModelMixin):
queryset = models.Person_relationship.objects.all()
serializer_class = Person_relationshipserializers1
throttle_classes = [PostSearchAnonRateThrottle]
def get(self,request):
user_id = int(request.GET.get("user_id"))
query_set = self.filter_queryset(self.get_queryset())
serializer_datas = self.serializer_class(instance=query_set.filter(person_id=user_id), many=True).data
result = ts.result_data(status.HTTP_200_OK, serializer_datas, " The query is successful ")
return Response(result)
my_middleware.py
class ExceptionChange:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_template_response(self, request, response):
if hasattr(response, 'data'):
data = response.data
status = None
message = None
if isinstance(data, dict) is True:
if "detail" in data.keys():
if "Request was throttled. " in data.get("detail"):
surplus_seconds = re.findall(r"\d+", data.get("detail"))[0]
del response.data["detail"]
status = 401
message = f" Access frequency is too high , Please be there. {surplus_seconds} Visit... In seconds "
else:
del response.data["detail"]
status = 401
message = " Login expired , Please login again "
if status and message:
response.data["status"] = status
response.data["data"] = None
response.data["message"] = message
return response
from ratelimit.decorators import ratelimit
from django.utils.decorators import method_decorator
class MyView(View):
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET', block=True))
def get(self, request):
pass
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET', block=True), name='get')
class MyOtherView(View):
def get(self, request):
pass
from ratelimit.decorators import ratelimit
@ratelimit(key='ip', rate='5/m', block=True)
def myview(request):
# same IP Access per minute exceeds 5 Time , Will be limited
return HttpResponse()