Skip to content

Instantly share code, notes, and snippets.

@mcos
Last active December 10, 2015 08:38
Show Gist options
  • Save mcos/4408647 to your computer and use it in GitHub Desktop.
Save mcos/4408647 to your computer and use it in GitHub Desktop.
Skeleton Base Class for Python HTTP Operations
class HttpBase(object):
def __init__(self, base_url, api_key):
self.base_url=base_url
self.api_key=api_key
self.headers = {'Content-Type': 'application/json',
'Accepts': 'application/json'}
self.http = httplib2.Http()
def get(self, path, data=None):
if not data:
data={}
data['api_key']=self.api_key
params = urlencode(data)
url = self.base_url % path
url = '?'.join([url, params])
response, content = self.http.request(url, method="GET",
headers=self.headers)
return self.process(response, content)
def post(self, path, body=None):
if not body:
body={}
body['api_key']=self.api_key
body = simplejson.dumps(body)
url = self.base_url % path
response, content = self.http.request(url, method="POST",
body=body, headers=self.headers)
return self.process(response, content)
def process(self, http_response, content):
if http_response.status!=200:
if 'message' in http_response:
raise Exception(http_response['message'])
else:
raise Exception()
code = http_response.status
body = simplejson.loads(content)
error_message = body.get('error_message', None)
response = Response(code, body, error_message, content, http_response)
return response
class Response(object):
def __init__(self, code=None, body=None, error_message=None, raw_body=None, raw_response=None):
self.code = code
self.body = body
self.error_message = error_message
self.raw_body = raw_body
self.raw_response = raw_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment