|
1 | 1 | """
|
2 | 2 | Parsers
|
3 | 3 | """
|
| 4 | +import json |
| 5 | + |
| 6 | +from django.conf import settings |
| 7 | +from django.utils import six |
4 | 8 | from rest_framework import parsers
|
5 | 9 | from rest_framework.exceptions import ParseError
|
6 | 10 |
|
7 | 11 | from . import utils, renderers, exceptions
|
8 | 12 |
|
9 | 13 |
|
10 |
| -class JSONParser(parsers.JSONParser): |
| 14 | +class JSONParser(parsers.BaseParser): |
11 | 15 | """
|
12 | 16 | A JSON API client will send a payload that looks like this:
|
13 | 17 |
|
@@ -58,7 +62,9 @@ def parse(self, stream, media_type=None, parser_context=None):
|
58 | 62 | """
|
59 | 63 | Parses the incoming bytestream as JSON and returns the resulting data
|
60 | 64 | """
|
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 | + |
62 | 68 | data = result.get('data')
|
63 | 69 |
|
64 | 70 | if data:
|
@@ -100,3 +106,18 @@ def parse(self, stream, media_type=None, parser_context=None):
|
100 | 106 |
|
101 | 107 | else:
|
102 | 108 | 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