Django-Tastypie has ImmediateHttpResponse
exception which allow to return to the client an immediate response:
raise ImmediateHttpResponse(response='a message')
Django has Http404, but i couldn't find a more universal exception like ImmediateHttpResponse
.
What technique do you use to return to client an immediate 400 response?
For example having model:
class Subscriber(Model):
def delete(self, *args, **kwargs):
raise ImmediateHttpResponse('Deleting subcribers is not allowed!')
and trying to delete an object would return to the client a 400
response with the given message.
I think what you want is a middleware which implements a process_exception.
It works like this: you raise an Exception on you view (e.g. ImmediateHttpResponse). If the exception is catched by your middleware, the middleware returns a response, in your case the with a status 400. If you don't catch the exception, Django will catch it in the end, returning a status 500 (server error), or other status.
The simplest example is a middleware that catches Http404. If you catch the exception Http404 in your middleware, you can return any response you want (status 200, 400, etc). If you don't catch (i.e. the process_exception method of you middleware returns None), Django will catch it for you and return a Response with status 404. This is actually the standard way of having your own custom exceptions that you want to respond in a custom way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With