为什么djangjsonencoder不处理代理对象?

2024-10-02 14:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这是djangjsonencoder的代码,它处理标准json编码器之外所需的大多数事情:

class DjangoJSONEncoder(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 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)
        else:
            return super(DjangoJSONEncoder, self).default(o)

但是当它试图编码一个代理对象时,它失败了django.utils.functional.__proxy__ object at 0x7f53c6325ed0> is not JSON serializable

通过将djangjsonencoder更改为:

^{pr2}$

但是写Django的人很聪明。如果这是真正的解决办法,他们可能已经做了。为什么他们没有这么做呢,对unicode的调用,与JSON编码结合在一起,这对djangjsonencoder来说是错误的修复?在

我甚至在Django文档中找到了一个reference to this problem,所以这并不像是未知的,我只是不明白为什么它不是默认值。在


Tags: tojsondatetimedatereturniftimeisinstance