James Brace
James Brace

Reputation: 85

RawPostDataException: You cannot access body after reading from request's data stream

I am hosting a site on Google Cloud and I got everything to work beautifully and then all of the sudden I start getting this error..

01:16:22.222
Internal Server Error: /api/v1/auth/login/ (/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py:124)
Traceback (most recent call last):
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 474, in dispatch
    response = self.handle_exception(exc)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 434, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 471, in dispatch
    response = handler(request, *args, **kwargs)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/authentication/views.py", line 42, in post
    data = json.loads(request.body)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/request.py", line 359, in __getattribute__
    return getattr(self._request, attr)
  File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/http/request.py", line 263, in body
    raise RawPostDataException("You cannot access body after reading from request's data stream")
RawPostDataException: You cannot access body after reading from request's data stream

I have no clue what this means, and endless googling has not solved my case in anyway..

Here's the code that is probably relevant:

views.py

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = AccountSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

serializer.py

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)
    confirm_password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'full_name', 'password', 'confirm_password')
        read_only_fields = ('created_at', 'updated_at',)

        def create(self, validated_data):
            return Account.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.username = validated_data.get('username', instance.username)

            instance.save()

            password = validated_data.get('password', None)
            confirm_password = validated_data.get('confirm_password', None)

            if password and confirm_password and password == confirm_password:
                instance.set_password(password)
                instance.save()

            update_session_auth_hash(self.context.get('request'), instance)

            return instance

Upvotes: 3

Views: 9705

Answers (3)

Arnab Biswas
Arnab Biswas

Reputation: 1002

Use request.data instead of request.body.

request.data does not read the data stream again.

Upvotes: 3

James Brace
James Brace

Reputation: 85

hey thanks for the response but I figured it out! It wasn't working because I found a small bug where I am able to access the login page even though I am already logged in, so the error was caused by trying to login again. I fixed the issue by redirecting to home page if login page is tried to be reached

Upvotes: 0

Nikhil Parmar
Nikhil Parmar

Reputation: 876

This is occuring is because you are trying to access the data from body

use -> data = json.loads(request.data)

Upvotes: 7

Related Questions