Python请求模块 - datetime.date不可序列化
我正在尝试使用Python的requests模块来调用一个服务,这个服务会返回一个包含日期时间对象的Python字典...
但是我遇到了以下错误,
File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 1733, in wrapper
json_response = dumps(rv)
File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 286, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 226, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 296, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 202, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2014, 4, 16) is not JSON serializable
调用语句:
r = requests.get('http://localhost:8089/allfeeds',verify=False)
print r.status_code
print r.text
2 个回答
0
这个错误信息来自服务器。下面这段只用标准库的代码:
from urllib2 import urlopen
r = urlopen('http://localhost:8089/allfeeds')
print r.code
print r.read().decode(r.info().getparam('charset') or 'utf-8')
也会产生同样的结果。r.code
应该是 5xx,这表示“服务器错误”。
datetime.date
不能直接转换成 JSON 格式;你需要修改你的服务器,把日期转换成字符串,比如用 some_date.isoformat()
,或者转换成数字(POSIX 时间戳),比如用 calendar.timegm(some_date.timetuple())
,假设 some_date
是 UTC 时间。具体可以参考这个链接:在 Python 中将 datetime.date 转换为 UTC 时间戳。
2
你的网页应用是用 bottle
写的吗?我怎么知道呢?
你可以试着在命令行里发一个请求,比如说:
$ curl http://localhost:8089/allfeeds
我觉得这个请求的结果应该和你在网页上看到的一样。
那行 print r.text
只是把返回的内容打印出来,并没有出错。
简单来说:requests
的调用是正常的,但你的网页服务返回的内容是个字符串,这看起来像是个问题。不过,这个问题出在你的网页应用上,而不是客户端。