change the dumps and loads hooks to accept string

The JSONRender and JSONParser need to be JSON serializable themselves,
so the loads_function and dumps_function are changed to accept strings
to work around it.
This commit is contained in:
Jiali Chen 2014-08-11 23:49:46 +08:00
parent 85e92b613b
commit 43546129ff
2 changed files with 16 additions and 6 deletions

View File

@ -13,7 +13,7 @@ from django.http.multipartparser import MultiPartParserError, parse_header, Chun
from rest_framework.compat import etree, six, yaml, force_text
from rest_framework.exceptions import ParseError
from rest_framework import renderers
import json
# import json
import datetime
import decimal
@ -48,7 +48,7 @@ class JSONParser(BaseParser):
media_type = 'application/json'
renderer_class = renderers.UnicodeJSONRenderer
loads_function = json.loads
loads_function = 'json.loads'
def parse(self, stream, media_type=None, parser_context=None):
"""
@ -59,7 +59,12 @@ class JSONParser(BaseParser):
try:
data = stream.read().decode(encoding)
return self.loads_function(data)
components = self.loads_function.split('.')
loads = __import__(components[0])
for comp in components[1:]:
loads = getattr(loads, comp)
return loads(data)
except ValueError as exc:
raise ParseError('JSON parse error - %s' % six.text_type(exc))

View File

@ -9,7 +9,7 @@ REST framework also provides an HTML renderer the renders the browsable API.
from __future__ import unicode_literals
import copy
import json
# import json
import django
from django import forms
from django.core.exceptions import ImproperlyConfigured
@ -55,7 +55,7 @@ class JSONRenderer(BaseRenderer):
encoder_class = encoders.JSONEncoder
ensure_ascii = True
charset = None
dumps_function = json.dumps
dumps_function = 'json.dumps'
# JSON is a binary encoding, that can be encoded as utf-8, utf-16 or utf-32.
# See: http://www.ietf.org/rfc/rfc4627.txt
# Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/
@ -82,7 +82,12 @@ class JSONRenderer(BaseRenderer):
except (ValueError, TypeError):
indent = None
ret = self.dumps_function(data, cls=self.encoder_class,
components = self.dumps_function.split('.')
dumps = __import__(components[0])
for comp in components[1:]:
dumps = getattr(dumps, comp)
ret = dumps(data, cls=self.encoder_class,
indent=indent, ensure_ascii=self.ensure_ascii)
# On python 2.x json.dumps() returns bytestrings if ensure_ascii=True,