From 8eb9dab0cab9ac6f91c502823dca1e0a8fd2339b Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 5 Dec 2023 19:56:53 +0000 Subject: [PATCH] Allowed json parser to parse request or bytes. --- django/http/parsers.py | 19 +++++++++---------- django/http/request.py | 9 ++------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/django/http/parsers.py b/django/http/parsers.py index 0fb2271fa2..236cd318ab 100644 --- a/django/http/parsers.py +++ b/django/http/parsers.py @@ -16,16 +16,11 @@ class BaseParser: def parse(self, data, request=None): pass - @property - def _supports_form_parsing(self): - form_media = ("application/x-www-form-urlencoded", "multipart/form-data") - return self.media_type in form_media - class FormParser(BaseParser): media_type = "application/x-www-form-urlencoded" - def parse(self, data, request=None): + def parse(self, request): from django.http import QueryDict # According to RFC 1866, the "application/x-www-form-urlencoded" @@ -42,7 +37,7 @@ class FormParser(BaseParser): class MultiPartParser(BaseParser): media_type = "multipart/form-data" - def parse(self, data, request=None): + def parse(self, request): if hasattr(request, "_body"): # Use already read data data = BytesIO(request._body) @@ -71,6 +66,10 @@ class MultiPartParser(BaseParser): class JSONParser(BaseParser): media_type = "application/json" - def parse(self, data, request=None): - # TODO enable strict mode. Like DRF. - return json.loads(data), MultiValueDict() + # TODO rename request -- it's not always one. + def parse(self, request): + from django.http import HttpRequest + + if isinstance(request, HttpRequest): + request = request.body + return json.loads(request), MultiValueDict() diff --git a/django/http/request.py b/django/http/request.py index 069a5e046e..77f776cd9e 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -376,13 +376,8 @@ class HttpRequest: if selected_parser: selected_parser.parsers = parser_list try: - if selected_parser._supports_form_parsing: - # TODO Not sure how to make these consistent. - data, self._files = parser.parse(None, self) - setattr(self, data_attr, data) - else: - data, self._files = parser.parse(self.body, self) - setattr(self, data_attr, data) + data, self._files = parser.parse(self) + setattr(self, data_attr, data) except Exception as e: # TODO 'application/x-www-form-urlencoded' didn't do this. # An error occurred while parsing POST data. Since when