Ho fatto funzionare il codice. Ho fatto i cambiamenti nel file seguenti
settings.py
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'utils.renderers.PalJSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)}
utils/renderers.py
from rest_framework.renderers import JSONRenderer
from rest_framework.utils.encoders import JSONEncoder
from json.encoder import encode_basestring_ascii, encode_basestring, INFINITY, _make_iterencode
class CustomJSONEncoder(JSONEncoder):
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
# Hack to enforce
c_make_encoder = None
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
def floatstr(o, allow_nan=self.allow_nan, _repr=lambda o: format(o, '.2f'), _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))
return text
if (_one_shot and c_make_encoder is not None and self.indent is None):
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
class PalJSONRenderer(JSONRenderer):
encoder_class = CustomJSONEncoder
fonte
2016-03-14 07:05:49
cosa c'è di sbagliato con il ritorno 3,333,333 mila? qualsiasi utente della tua API può visualizzarlo come 3.33. Lascia che il client gestisca la formattazione. – Ali
In Android, è necessario specificare il tipo di dati come float, int o long. supponiamo che inizialmente i dati fossero ** 4.56 ** ma ora arrivano ** 3.3333333 **. quindi è molto difficile cambiare a lungo tutti i tipi di dati float. ecco perché ho bisogno di una soluzione a ** back-end ** non client end. –
Suppongo che vinay abbia ragione, ho anche affrontato lo stesso problema. convertirli dal lato client (in particolare Android non è una buona idea) @vinaykumar, le persone saranno felici di rispondere alla tua domanda, se annoti anche i tuoi tentativi (cosa hai provato) con la domanda. Suppongo che tu abbia bisogno di monkeypatch su json.dumps che viene chiamato dalla classe JSONEncode. – Pawan