Skip to content

Commit b2bb264

Browse files
author
Hamed Ahmadi
committed
Making JSONParser python 3 compatible
1 parent 6082aae commit b2bb264

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

rest_framework_json_api/parsers.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
"""
22
Parsers
33
"""
4+
import json
5+
6+
from django.conf import settings
47
from rest_framework import parsers
58
from rest_framework.exceptions import ParseError
69

710
from . import utils, renderers, exceptions
811

912

10-
class JSONParser(parsers.JSONParser):
13+
class JSONParser(parsers.BaseParser):
1114
"""
1215
A JSON API client will send a payload that looks like this:
1316
@@ -58,7 +61,9 @@ def parse(self, stream, media_type=None, parser_context=None):
5861
"""
5962
Parses the incoming bytestream as JSON and returns the resulting data
6063
"""
61-
result = super(JSONParser, self).parse(stream, media_type=media_type, parser_context=parser_context)
64+
65+
result = self._convert_context_to_json(stream, media_type, parser_context)
66+
6267
data = result.get('data')
6368

6469
if data:
@@ -100,3 +105,18 @@ def parse(self, stream, media_type=None, parser_context=None):
100105

101106
else:
102107
raise ParseError('Received document does not contain primary data')
108+
109+
def _convert_context_to_json(self, stream, media_type=None, parser_context=None):
110+
parser_context = parser_context or {}
111+
112+
try:
113+
string = stream.read()
114+
if hasattr(string, 'decode'):
115+
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
116+
data = string.decode(encoding)
117+
else:
118+
data = string
119+
120+
return json.loads(data)
121+
except ValueError as exc:
122+
raise ParseError('JSON parse error - %s' % six.text_type(exc))

0 commit comments

Comments
 (0)