0

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
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 1
    I believe the service that is returning this response has to use `datetime.strftime` to convert it to string. Not sure if you on the receiving end can prevent this error. – shaktimaan Apr 17 '14 at 00:11
  • gtw, use of `verify=False` is not needed as it affects only https (and controls weather it shall verify validity of used certificates or not). – Jan Vlcinsky Apr 23 '14 at 11:56

2 Answers2

2

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.

Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98
0

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670