Skip to content

Commit bc843f6

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

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

rest_framework_json_api/parsers.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
"""
22
Parsers
33
"""
4+
import json
5+
6+
from django.conf import settings
7+
from django.utils import six
48
from rest_framework import parsers
59
from rest_framework.exceptions import ParseError
610

711
from . import utils, renderers, exceptions
812

913

10-
class JSONParser(parsers.JSONParser):
14+
class JSONParser(parsers.BaseParser):
1115
"""
1216
A JSON API client will send a payload that looks like this:
1317
@@ -58,7 +62,9 @@ def parse(self, stream, media_type=None, parser_context=None):
5862
"""
5963
Parses the incoming bytestream as JSON and returns the resulting data
6064
"""
61-
result = super(JSONParser, self).parse(stream, media_type=media_type, parser_context=parser_context)
65+
66+
result = self._convert_context_to_json(stream, media_type, parser_context)
67+
6268
data = result.get('data')
6369

6470
if data:
@@ -100,3 +106,18 @@ def parse(self, stream, media_type=None, parser_context=None):
100106

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

0 commit comments

Comments
 (0)