简体   繁体   English

Python请求模块-datetime.date不可序列化

[英]Python request module - datetime.date is not serialiable

Im trying to use Python requests module to call a service which returns a Python dict that contains a datetime object... 我试图使用Python请求模块来调用服务,该服务返回包含日期时间对象的Python字典...

I get this following errror, 我得到这个错误

  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

Call stmt: 致电stmt:

r = requests.get('http://localhost:8089/allfeeds',verify=False)
print r.status_code
print r.text

Is your web app written using bottle ? 您的网络应用程序是使用bottle编写的吗? How do I know that? 我怎么知道

Try to make the same call from command line, eg: $ curl http://localhost:8089/allfeeds 尝试从命令行进行相同的调用,例如: $ curl http://localhost:8089/allfeeds

I think, that the output of such request will be exactly the same. 我认为,此类请求的输出将完全相同。

the line print r.text is just printing the response - not breaking. print r.text只是打印响应-不中断。

In short: the requests call works perfectly well, but your web service is returning a string, which looks like a problem. 简而言之: requests调用可以很好地工作,但是您的Web服务正在返回一个字符串,这似乎是一个问题。 But the problem is in your web app, not on client side. 但是问题出在您的Web应用程序中,而不是客户端。

The stacktrace is from the server. stacktrace来自服务器。 The stdlib-only code: 仅限stdlib的代码:

from urllib2 import urlopen

r = urlopen('http://localhost:8089/allfeeds')
print r.code 
print r.read().decode(r.info().getparam('charset') or 'utf-8')

would produce the same result. 会产生相同的结果。 r.code should be 5xx, meaning "Server Error". r.code应该为5xx,表示“服务器错误”。

datetime.date is not JSON serializable; datetime.date不可序列化为JSON; you should modify your server to convert dates into strings eg, some_date.isoformat() or numbers (POSIX timestamp) eg, calendar.timegm(some_date.timetuple()) assuming some_date is in UTC, see Converting datetime.date to UTC timestamp in Python . 您应该修改服务器以将日期转换为字符串,例如some_date.isoformat()或数字(POSIX时间戳),例如calendar.timegm(some_date.timetuple())假设some_date在UTC中,请参阅将datetime.date转换为UTC时间戳Python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM