user1050619
user1050619

Reputation: 20856

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...

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:

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

Upvotes: 0

Views: 2007

Answers (2)

jfs
jfs

Reputation: 414079

The stacktrace is from the server. The stdlib-only code:

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".

datetime.date is not JSON serializable; you should modify your server to convert dates into strings e.g., some_date.isoformat() or numbers (POSIX timestamp) e.g., calendar.timegm(some_date.timetuple()) assuming some_date is in UTC, see Converting datetime.date to UTC timestamp in Python.

Upvotes: 0

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44092

Is your web app written using bottle? How do I know that?

Try to make the same call from command line, e.g.: $ 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.

In short: the requests call works perfectly well, but your web service is returning a string, which looks like a problem. But the problem is in your web app, not on client side.

Upvotes: 2

Related Questions