diff options
| author | Tom Christie | 2012-09-03 13:30:20 +0100 |
|---|---|---|
| committer | Tom Christie | 2012-09-03 13:30:20 +0100 |
| commit | a25b4be4418a2a94e38a77b13cc234ca68e8322c (patch) | |
| tree | 8b14904314ed87d8f0f15bc2a6ebb30c1cf570b9 /djangorestframework/utils | |
| parent | ebbaff0853d49cd436b416beeb28220922bfc977 (diff) | |
| download | django-rest-framework-a25b4be4418a2a94e38a77b13cc234ca68e8322c.tar.bz2 | |
Support generators
Diffstat (limited to 'djangorestframework/utils')
| -rw-r--r-- | djangorestframework/utils/encoders.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/djangorestframework/utils/encoders.py b/djangorestframework/utils/encoders.py new file mode 100644 index 00000000..3cd2e8e1 --- /dev/null +++ b/djangorestframework/utils/encoders.py @@ -0,0 +1,33 @@ +import datetime +import decimal +from django.utils import timezone +from django.utils import simplejson as json + + +class JSONEncoder(json.JSONEncoder): + """ + JSONEncoder subclass that knows how to encode date/time and decimal types. + """ + def default(self, o): + # See "Date Time String Format" in the ECMA-262 specification. + if isinstance(o, datetime.datetime): + r = o.isoformat() + if o.microsecond: + r = r[:23] + r[26:] + if r.endswith('+00:00'): + r = r[:-6] + 'Z' + return r + elif isinstance(o, datetime.date): + return o.isoformat() + elif isinstance(o, datetime.time): + if timezone.is_aware(o): + raise ValueError("JSON can't represent timezone-aware times.") + r = o.isoformat() + if o.microsecond: + r = r[:12] + return r + elif isinstance(o, decimal.Decimal): + return str(o) + elif hasattr(o, '__iter__'): + return [i for i in o] + return super(JSONEncoder, self).default(o) |
