Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Django HttpRequest body in Middleware

I have a PUT request and I want to update the values of few of the params in my middleware. I know there is no way to directly access the PUT params, so I'm accessing them via request.body.

Once these values have been updated, I need to pass this request onto the view. However, if I try to do:

request.body = new_content

in my middleware, I get:

AttributeError: can't set attribute

Is there any way to update these params in the middleware and pass them on?

like image 867
sparknoob Avatar asked Mar 30 '14 04:03

sparknoob


1 Answers

request.body is defined as a property in HttpRequest class.

This is code how body property looks like:

@property
def body(self):
    if not hasattr(self, '_body'):
        if self._read_started:
            raise RawPostDataException("You cannot access body after reading from request's data stream")
        try:
            self._body = self.read()
        except IOError as e:
            six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
        self._stream = BytesIO(self._body)
    return self._body

The aproach that I will use there is to modify _body attribute in the process_request method. The return value here is None, because I want that Django continue processing that request through middleware until to the appropriate view.

class MidddlewareWithHttpPutRequest:
    def process_request(self, request):
        data = getattr(request, '_body', request.body)
        request._body = data + '&dummy_param=1'
        # if you call request.body here you will see that new parameter is added
        return None
like image 134
P̲̳x͓L̳ Avatar answered Oct 21 '22 23:10

P̲̳x͓L̳