无法从 Cherrypy 将日期时间序列化为 JSON

2024-02-27

我正在尝试发送记录列表以响应 Ajax 查询。这很有效,除非当我的进程因错误而失败时结果包含日期时间字段datetime.date(2011, 11, 1) is not JSON serializable.

我试图将我找到的答案结合起来类似的问题 https://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript这里有说明CherryPy 文档 http://docs.cherrypy.org/dev/refman/lib/jsontools.html使用自定义 json_out 编码器,但我不清楚该函数必须具有什么签名。我写的函数是:

 def json_encoder(thing):

      if hasattr(thing, 'isoformat'):
           return thing.isoformat()
      else:
           return str(thing)

and now any使用 json_out (即使输出中没有日期时间)给了我错误TypeError: json_encoder() takes exactly 1 argument (0 given)。但是如果编码器不接受参数,它如何接收要编码的对象?

(另外,我假设我使用str(thing)因为默认的编码方法是错误的,这应该通过调用 json 编码的默认处理程序来完成,但我不确定如何调用该方法)。


我遇到了同样的问题(Python 3.2,Cherrypy 3.2.2),我用以下代码解决了它:

import cherrypy
import json
import datetime
class _JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.date):
            return obj.isoformat()
        return super().default(obj)
    def iterencode(self, value):
        # Adapted from cherrypy/_cpcompat.py
        for chunk in super().iterencode(value):
            yield chunk.encode("utf-8")

json_encoder = _JSONEncoder()

def json_handler(*args, **kwargs):
    # Adapted from cherrypy/lib/jsontools.py
    value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
    return json_encoder.iterencode(value)

然后你就可以使用Cherrypyjson_out装饰器:

class Root:
     @cherrypy.expose
     @cherrypy.tools.json_out(handler=json_handler)
     def default(self, *args, **kwargs):
         ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法从 Cherrypy 将日期时间序列化为 JSON 的相关文章

随机推荐