Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Django have exception for an immediate http response?

Tags:

python

django

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.

like image 815
warvariuc Avatar asked Mar 24 '23 04:03

warvariuc


1 Answers

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.

like image 89
Jorge Leitao Avatar answered Apr 05 '23 23:04

Jorge Leitao