Skip to content

Instantly share code, notes, and snippets.

@HarryR
Created April 24, 2014 12:32
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 HarryR/11253031 to your computer and use it in GitHub Desktop.
Save HarryR/11253031 to your computer and use it in GitHub Desktop.
Sociagram Python API
class SociagramApi(object):
"""
Ported over from Sociagrams really shoddy Zend based API client (lololol, many fails, very 'enterprise')
"""
def __init__(self, key=None, secret=None):
self.api_url = 'https://api.sociagram.com/v1'
self.key = settings.SOCIAGRAM_API_KEY if key is None else key
self.secret = settings.SOCIAGRAM_API_SECRET if secret is None else secret
def makeRequest (self, uri, method='get', get=None, post=None):
full_uri = self.api_url.rstrip('/') + '/' + uri.lstrip('/')
parsed_uri = urlparse(full_uri)
nonce = os.urandom(16).encode('hex')
timestmap = str(int(time.time()))
if method == 'post':
if post is None:
post = {}
post['request_nonce'] = nonce
post['request_key'] = self.key
post['request_timestamp'] = timestmap
elif method == 'get':
if get is None:
get = {}
get['request_nonce'] = nonce
get['request_key'] = self.key
get['request_timestamp'] = timestmap
validation_string = self.createValidationString(parsed_uri.path, method, get, post)
signature = self.signature(validation_string, self.secret)
if method == 'post':
post['request_signature'] = signature
elif method == 'get':
get['request_signature'] = signature
if method == 'get':
r = requests.get(full_uri, params=get)
elif method == 'post':
r = requests.post(full_uri, params=post)
r.raise_for_status()
return r.json
def createValidationString(self, uri, method='get', get=None, post=None ):
assert uri is not None
assert get is not None
assert 'request_key' in get
assert 'request_nonce' in get
# Merge in POST vars
params = get.items()
if post is not None:
params += post.items()
params += [('request_method', method.lower()), ('request_path', uri.lower())]
params = sorted([item for item in params if item[0] != 'request_signature'])
validation_string = ''
for pair in params:
if len(validation_string) > 0:
validation_string += '&'
if pair[0] != 'request_path':
validation_string += '%s=%s' % (urllib.quote(pair[0]), urllib.quote(pair[1]))
else:
validation_string += '%s=%s' % (pair[0], pair[1])
return validation_string
def signature(self, base_string, consumer_secret):
mac = hmac.new(consumer_secret, base_string, hashlib.sha1)
return urllib.quote(base64.b64encode(mac.digest()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment