Does Django have an exception for an immediate HTTP response?

Django-Tastypie has an ImmediateHttpResponse exception, which allows you to immediately return a response to the client:

 raise ImmediateHttpResponse(response='a message') 

Django has Http404 , but I could not find a more universal exception like ImmediateHttpResponse .

What technique do you use to return an immediate 400 response to a customer?

For example, with a model:

 class Subscriber(Model): def delete(self, *args, **kwargs): raise ImmediateHttpResponse('Deleting subcribers is not allowed!') 

and an attempt to delete the object will return a 400 response to the client with this message.

+4
source share
2 answers

I think you want a middleware that implements process_exception .

It works as follows: you throw an exception when viewing (e.g. ImmediateHttpResponse). If the exception falls into your middleware, the middleware returns a response, in your case with a status of 400. If you do not catch the exception, Django will catch it at the end, returning the status 500 (server error) or another status.

The simplest example is the middleware that catches Http404. If you catch the Http404 exception in your middleware, you can return any answer you want (status 200, 400, etc.). If you don't catch (i.e. the process_exception method for your middleware returns None), Django will catch it for you and return a response with a status of 404. This is actually the standard way to have your own custom exceptions that you want to respond to in a custom way.

+4
source

This is not an exception, but there is an HttpResponseBadRequest which is your regular HttpResponse , but with 400 .

The Http404 exception is just an empty Exception class , there is nothing special:

 class Http404(Exception): pass 

This way you can easily create your own if you need:

 class Http400(Exception): pass 

ImmediateHttpResponse not much different from Http404 in that it is also a general Exception , but with a specific property, which makes it more similar to HttpResponseBadRequest :

 class ImmediateHttpResponse(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 @property def response(self): return self._response 
+2
source

Source: https://habr.com/ru/post/1491403/


All Articles