How can I log all my requests and responses (headers and body) in Django using a middleware? I'm using Django 2.2 with Django rest framework, so sometimes the requests and responses are original Django type, sometimes of drf. The app is served behind gunicorn. I've developed middleware but the main problem is I can't read request's body twice as it gives me error.
I originally tried to do something like request = copy.copy(request)
but clearly it's a mistake because shallow copying does not copy nested objects. So the correct approach is (__call__
is middleware's class instance method):
def __call__(self, request):
request_body = copy.copy(request.body)
# Here goes more code for further processing
# and now I can safely use request_body before or after
# the view code runs
As Felix Eklöf suggested, you can also use str(request.body)
and python will handle copying the body contents, cause strings are immutable in python. (I guess it has better readability too).