eadwinCode / django-ninja-extra

Django Ninja Extra - Class-Based Utility and more for Django Ninja(Fast Django REST framework)
https://eadwincode.github.io/django-ninja-extra/
MIT License
395 stars 33 forks source link

Throttle response message customization #202

Open tmorgan497 opened 1 week ago

tmorgan497 commented 1 week ago

Hi, is there a way to change the default message in the throttle response to remove the time remaining message?

For example, instead of this:

{
  "detail": "Request was throttled. Expected available in 53 seconds."
}

A way to customize it to this:

{
  "detail": "Too many requests. Please try again later."
}

Potential implementation:

class User6MinRateThrottle(UserRateThrottle):
    """User 6 per min. rate limit."""

    rate = "6/min"
    scope = "minutes"

    def throttle_response(self, request, response):
        if response.status_code = 429:
            return JsonResponse({"detail": "Too many requests. Please try again later."}, status=429)
        return response

@api_controller("shop/", throttle=[User6MinRateThrottle()])
class ProductController:
    """Product API controller."""

    @route.post("/product")
    def create_product(
        self,
        payload: ProductCreateSchema,
    ) -> dict:
        """Create product API endpoint."""
        product = Product.objects.create(
            name=payload.name,
            description=payload.description,
            price=payload.price,
        )
        return {
            "id": product.id,
            "name": product.name,
            "description": product.description,
            "price": product.price,
        }
eadwinCode commented 5 days ago

@tmorgan497 You may have to create this ticket on django-ninja repo. because the base class for Throttling have been moved to django-ninja repo.