Django Function-Based Views: Checking Remaining Throttle Limits
To check how many throttle limits are left in a function-based view in Django, you can use the 'throttle_scope' property of the view class. This property returns a string representing the name of the throttle scope for the view. You can then use this string to get the number of remaining requests for the throttle limit using the 'throttle' module.
Here's an example:
from rest_framework.throttling import SimpleRateThrottle, get_throttle_scope
class MyView(APIView):
throttle_classes = [SimpleRateThrottle]
throttle_scope = 'my_throttle_scope'
def get(self, request):
# Get the throttle scope for this view
throttle_scope = get_throttle_scope(self)
# Get the number of remaining requests for the throttle limit
throttle = SimpleRateThrottle()
remaining = throttle.get_num_requests(request, throttle_scope)
# Do something with the remaining requests
...
return Response(...)
In this example, we define a 'MyView' class that uses the 'SimpleRateThrottle' class to throttle requests based on a rate limit. We also define a 'throttle_scope' property for the view, which is used by the 'SimpleRateThrottle' class to determine the throttle scope for each request.
In the 'get' method of the view, we use the 'get_throttle_scope' function to get the throttle scope for the view. We then create an instance of the 'SimpleRateThrottle' class and use its 'get_num_requests' method to get the number of remaining requests for the throttle limit. Finally, we do something with the remaining requests and return a response.
原文地址: https://www.cveoy.top/t/topic/mUPq 著作权归作者所有。请勿转载和采集!