Barry A. Warsaw added the comment:

On Aug 30, 2014, at 07:34 PM, Ethan Furman wrote:

>In other words, this was a bug that no one noticed for many many releases,
>and I'm not sure we should fix it in 2.7 now.
>
>Arguments for fixing?

-1 on fixing it, but we *can* document workarounds.  Here's what I use in
Mailman 3.

class ExtendedEncoder(json.JSONEncoder):
    """An extended JSON encoder which knows about other data types."""

    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, timedelta):
            # as_timedelta() does not recognize microseconds, so convert these
            # to floating seconds, but only if there are any seconds.
            if obj.seconds > 0 or obj.microseconds > 0:
                seconds = obj.seconds + obj.microseconds / 1000000.0
                return '{0}d{1}s'.format(obj.days, seconds)
            return '{0}d'.format(obj.days)
        elif isinstance(obj, Enum):
            # It's up to the decoding validator to associate this name with
            # the right Enum class.
            return obj.name
        return json.JSONEncoder.default(self, obj)

(Frankly, I wish it was easier to extend the encoder, e.g. by registering
callbacks for non-standard types.)

I don't automatically decode enums because on PUTs, POSTs, and PATCHs, I know
which attributes should be enums, so I can convert them explicitly when I
validate input forms.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue22297>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to