Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Python routine to build a fake httplib2.Response object out of a Requests object, two bottlecaps and some twine.
def fakeResponse(req):
""" Replacing httplib2 with Requests without rewriting the planet (har har)
means that we need to assemble a fake Response object out of the header set
returned by a Request. Shenanigans ahead. """
import httplib2
info = dict()
info['status'] = 200
fake = httplib2.Response(info)
for keys in req.headers:
setattr(fake, str(keys).lower(), req.headers[keys])
# We're handling the status like this because httplib2 expects an int there,
# but some web servers will hand you "200 OK" instead of 200, and Requests
# doesn't always do the right thing.
fake.status = int(str(req.status_code).split(' ')[0])
# fromcache and versions have no equivalent in Requests that I can see, so
# we're just going to lie about it. Per the docs, "11" means "HTTP/1.1",
# so, this might conceivably break something in a future HTTP2-friendly world.
fake.fromcache = False
fake.version = '11'
fake.reason = req.reason
fake.previous = (req.history[-2]).url
fake.previous = req.url
setattr(fake, 'content-location', req.url)
# This is particular to Planet's in-house caching sytem.
fake['-content-hash'] = ''
return fake
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment