Skip to content Skip to sidebar Skip to footer

Does Django Have Exception For An Immediate Http Response?

Django-Tastypie has ImmediateHttpResponse exception which allow to return to the client an immediate response: raise ImmediateHttpResponse(response='a message') Django has Http404

Solution 1:

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.

Solution 2:

It is not an exception, but there is HttpResponseBadRequest, which is your normal HttpResponse but with 400.

The Http404 exception is simply an empty Exception class, there is nothing special about it:

classHttp404(Exception):
    pass

So you can easily create your own if you must:

classHttp400(Exception):
    pass

ImmediateHttpResponse isn't that much different than Http404 in that its also a generic Exception but with a specific property, which makes it more like HttpResponseBadRequest:

classImmediateHttpResponse(TastypieError):
    """
    This exception is used to interrupt the flow of processing to immediately
    return a custom HttpResponse.

    Common uses include::

        * for authentication (like digest/OAuth)
        * for throttling

    """
    _response = HttpResponse("Nothing provided.")

    def__init__(self, response):
        self._response = response

    @propertydefresponse(self):
        return self._response

Post a Comment for "Does Django Have Exception For An Immediate Http Response?"