Skip to content

Instantly share code, notes, and snippets.

@rduplain
Created October 5, 2011 19:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/1265409 to your computer and use it in GitHub Desktop.
Save rduplain/1265409 to your computer and use it in GitHub Desktop.
Simple Python HTTP client for tests, maintains cookies.
import cookielib
import urllib
import urllib2
class Client(object):
def __init__(self):
self.cookie_jar = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPCookieProcessor(self.cookie_jar))
urllib2.install_opener(self.opener)
def get(self, url, headers={}):
"""HTTP GET
url should be a string containing a valid URL.
headers should be a dictionary
"""
request = urllib2.Request(url, headers=headers)
return self.execute_request(request)
def post(self, url, data=None, headers={}):
"""HTTP POST
url should be a string containing a valid URL.
data should be a url-encodable dictionary
headers should be a dictionary
"""
if data is None:
postdata = None
else:
postdata = urllib.urlencode(data)
request = urllib2.Request(url, postdata, headers)
return self.execute_request(request)
def execute_request(self, request):
response = self.opener.open(request)
response.status_code = response.getcode()
response.data = response.read()
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment