Created
July 8, 2012 00:53
-
-
Save amccloud/3068820 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, json, re | |
def camelcase_to_underscore(text, lower=True): | |
text = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) | |
text = re.sub('([a-z0-9])([A-Z])', r'\1_\2', text) | |
if lower: | |
text = text.lower() | |
return text | |
def underscore_to_camelcase(text, capfirst=False): | |
text = ''.join(word.capitalize() or '_' for word in text.split('_')) | |
if not capfirst: | |
text = text[0].lower() + text[1:] | |
return text | |
def dot_to_underscore(text, lower=True): | |
text = text.replace('.', '_') | |
if lower: | |
text = text.lower() | |
return text | |
def dot_to_camelcase(text, capfirst=False): | |
text = dot_to_underscore(text, lower=False) | |
text = underscore_to_camelcase(text, capfirst=capfirst) | |
return text | |
class Apy(object): | |
__base_url__ = '' | |
def __init__(self, base_url=None, **kwargs): | |
if base_url: | |
self.__base_url__ = base_url | |
self.__base_properties__ = kwargs | |
def __getattr__(self, name): | |
method = self.__tomethod__(name) | |
def call(*args, **kwargs): | |
url = self.__url__(method, args) | |
properties = self.__base_properties__ | |
properties.update(kwargs) | |
for key in properties.keys(): | |
properties[self.__toproperty__(key)] = properties.pop(key) | |
return self.__request__(url, properties) | |
return call | |
def __tomethod__(self, name): | |
return name | |
def __toproperty__(self, name): | |
return name | |
def __url__(self, method, args): | |
url = self.__base_url__ + method | |
if args: | |
url += u'/' + u'/'.join(map(unicode, args)) | |
return url | |
def __request__(self, url, params): | |
response = requests.get(url, params=params) | |
if not self.__validate__(response): | |
return | |
return self.__parse__(response) | |
def __validate__(self, response): | |
if not 200 <= response.status_code < 300: | |
raise Exception(self.__parse__(response)) | |
return True | |
def __parse__(self, response): | |
return response.json | |
class Zappos(Apy): | |
__base_url__ = 'http://api.zappos.com/' | |
def __tomethod__(self, name): | |
return underscore_to_camelcase(name, capfirst=True) | |
def __toproperty__(self, name): | |
return underscore_to_camelcase(name, capfirst=False) | |
z = Zappos(key='YOUR_API_KEY') | |
print z.core_value() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment