Skip to content

Instantly share code, notes, and snippets.

@zed
Created December 8, 2013 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/7865274 to your computer and use it in GitHub Desktop.
Save zed/7865274 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Retrieve json using t.w.c.getPage().
http://stackoverflow.com/questions/20460352/python-json-decoder-error
"""
import json
import sys
import urllib
from twisted.internet import reactor
from twisted.python.util import println
from twisted.web.client import getPage
path = 'ip' if len(sys.argv) < 2 else sys.argv[1]
d = getPage('http://httpbin.org/' + urllib.quote(path),
timeout=20, headers={'Accept': 'application/json'})
d.addCallback(json.loads) # parse response as json
d.addBoth(println) # print parsed data or an error
d.addBoth(lambda _: reactor.stop()) # exit
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment