0

I am using Django REST Framework, and following this django logging - django.request logger and extra context answer to include custom data to my log records. When trying to access record.request.data inside filter() (to store it to record.data as that answer suggests) I get RawPostDataException: You cannot access body after reading from request's data stream. I have tried many things, none of which worked. Cannot manually rewind the request's data stream, nor get a fresh copy of the request object. I never manually access request.body, as the SO answers suggest avoiding. Any help would be appreciated.

Here is the code:

import logging

from rest_framework.request import Request
from rest_framework.settings import api_settings


class RequestInfoFilter(logging.Filter):

    def filter(self, record):
        parsers = [parser() for parser in api_settings.DEFAULT_PARSER_CLASSES]
        authenticators = [
            auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES]
        request = Request(
            record.request, parsers=parsers, authenticators=authenticators)

        record.method = request.method
        record.query_params = request.query_params
        record.data = request.data  # RawPostDataException: You cannot access body after reading from request's data stream

        return True

Note that this happens only when logging views that access request.data themselves. If they don't, no error occurs.

Indy
  • 1
  • 1
  • `request.data` is accessible in classes which inherit from `Apiview` or if you're using function base add a decorator `@apiview(['GET'])` – Atif Shafi Oct 04 '21 at 14:38
  • @AtifShafi I know but this doesn't answer my question. As shown in the code, I explicitly create a `rest_framework.request.Request` object, which, then, has a `data` attribute. It's just that if `request.data` has been accessed by the view before it reaches the log filter, I get `RawPostDataException`. If it hasn't been accessed I don't get the error. – Indy Oct 04 '21 at 15:14
  • Just to confirm, it doesn't work with `record.request.data`? – Brian Destura Oct 04 '21 at 23:54
  • @BrianD If the view that is being logged accesses/references `request.data`, then `record.request.data` causes a `RawPostDataException`, indeed. – Indy Oct 05 '21 at 08:05

0 Answers0