class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.slumber._add_callback({'method': add_transaction_id}) self.api = self.slumber.api.v1 def parse_res(self, res): if res == '': return {} if isinstance(res, (str, unicode)): return json.loads(res) return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) except HttpClientError as e: res = self.parse_res(e.response.content) for key, value in res.iteritems(): res[key] = [self.errors[v] for v in value if v in self.errors] return {'errors': res} return res
class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.api = self.slumber.api.v1 def parse_res(self, res): if res == '': return {} if isinstance(res, (str, unicode)): return json.loads(res) return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) except HttpClientError as e: res = self.parse_res(e.response.content) for key, value in res.iteritems(): res[key] = [self.errors[v] for v in value] return {'errors': res} return res
def __init__(self, config=None): self.config = self.parse(config) self.api = API(config['server']) self.api.activate_oauth(settings.SOLITUDE_OAUTH.get('key'), settings.SOLITUDE_OAUTH.get('secret')) self.encoder = None self.filter_encoder = urllib.urlencode
class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.slumber._add_callback({'method': add_transaction_id}) self.api = self.slumber.api.v1 def parse_res(self, res): if res == '': return {} if isinstance(res, (str, unicode)): return json.loads(res) return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) if getattr(res, 'status_code', None) == 304: raise ResourceNotModified() except HttpClientError as e: if e.response.status_code == 412: log.error('An attempt to update an already modified resource ' 'has been made.') raise ResourceModified() else: res = self.parse_res(e.response.content) for key, value in res.iteritems(): res[key] = [ self.errors[v] for v in value if v in self.errors ] return {'errors': res} return res
class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get("key"), oauth.get("secret")) self.slumber._add_callback({"method": add_transaction_id}) self.api = self.slumber.api.v1 def parse_res(self, res): if res == "": return {} if isinstance(res, (str, unicode)): return json.loads(res) return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) if getattr(res, "status_code", None) == 304: raise ResourceNotModified() except HttpClientError as e: if e.response.status_code == 412: log.error("An attempt to update an already modified resource " "has been made.") raise ResourceModified() else: res = self.parse_res(e.response.content) for key, value in res.iteritems(): res[key] = [self.errors[v] for v in value if v in self.errors] return {"errors": res} return res
def _tier(server, tier): srv = API(servers[server]) if server not in session['oauth']: raise ValueError('No key in session for %s.' % server) auth = session['oauth'][server] srv.activate_oauth(auth['key'], auth['secret']) return srv.by_url('/api/v1/services/price-currency/{0}/'.format(tier), parser=safe_parser)
def __init__(self, reference_name): self.config = settings.ZIPPY_CONFIGURATION.get(reference_name) self.api = None if self.config: self.api = API(self.config['url'], append_slash=False) self.api.activate_oauth(self.config['auth']['key'], self.config['auth']['secret'], params={'oauth_token': 'not-implemented'}) else: log.warning('No config for {ref}; oauth disabled' .format(ref=reference_name))
class Client(object): def __init__(self, config=None): self.config = self.parse(config) self.api = API(config['server']) self.api.activate_oauth(settings.SOLITUDE_OAUTH.get('key'), settings.SOLITUDE_OAUTH.get('secret')) self.encoder = None self.filter_encoder = urllib.urlencode def parse(self, config=None): return {'server': config.get('server')}
class Client(object): def __init__(self, reference_name): self.config = settings.ZIPPY_CONFIGURATION.get(reference_name) self.api = None if self.config: self.api = API(self.config['url'], append_slash=False) self.api.activate_oauth(self.config['auth']['key'], self.config['auth']['secret']) else: log.warning('No config for {ref}; oauth disabled' .format(ref=reference_name))
class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.slumber._add_callback({'method': add_transaction_id}) self.api = self.slumber.api.v1 def parse_res(self, res): if res == '': return {} if isinstance(res, (str, unicode)): try: return json.loads(res) except ValueError: log.error('Received unexpected non-JSON error: {res}' .format(res=res)) raise return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) if getattr(res, 'status_code', None) == 304: raise ResourceNotModified() except HttpClientError as e: if e.response.status_code == 412: log.error('An attempt to update an already modified resource ' 'has been made.') raise ResourceModified() else: res = self.parse_res(e.response.content) for key, value in res.iteritems(): res[key] = [self.errors[v] for v in value if v in self.errors] return {'errors': res} return res
class SlumberWrapper(object): """ A wrapper around the Slumber API. """ def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.slumber._add_callback({'method': add_transaction_id}) self.api = self.slumber.api.v1 def parse_res(self, res): if res == '': return {} if isinstance(res, (str, unicode)): try: return json.loads(res) except ValueError: log.error('Received unexpected non-JSON error: {res}'.format( res=res)) raise return res def safe_run(self, command, *args, **kwargs): try: res = command(*args, **kwargs) if getattr(res, 'status_code', None) == 304: raise ResourceNotModified() except HttpClientError as e: if e.response.status_code == 412: log.error('An attempt to update an already modified resource ' 'has been made.') raise ResourceModified() else: # Solitude returns error codes rather than error text. # For example: {"pin": ["PIN_ONLY_NUMBERS"]}. res = self.parse_res(e.response.content) return {'errors': res} return res
def __init__(self, reference_name): proxy = settings.ZIPPY_PROXY if not settings.ZIPPY_PROXY.endswith('/'): proxy = proxy + '/' self.config = settings.ZIPPY_CONFIGURATION.get(reference_name) self.api = API(proxy + reference_name, append_slash=False)
def __init__(self, config=None): self.config = self.parse(config) self.api = API(config['server']) self.encoder = None self.filter_encoder = urllib.urlencode
class Client(object): def __init__(self, config=None): self.config = self.parse(config) self.api = API(config["server"]) self.api.activate_oauth(settings.SOLITUDE_OAUTH.get("key"), settings.SOLITUDE_OAUTH.get("secret")) self.encoder = None self.filter_encoder = urllib.urlencode def call_uri(self, uri, method="get", data=None): """If you were given a URI by Solitude, pass it here and get that the value back. Since the URLs are relative, they couldn't simply be passed to `call()`. This handles all the prefixing and whatnot. """ uri = uri.lstrip("/") return self.call("%s/%s" % (self.config["server"], uri), method, data) def _url(self, context, name, pk=None): url = "%s/%s/%s/" % (self.config["server"], context, name) if pk: url = "%s%s/" % (url, pk) return url def parse(self, config=None): config = { "server": config.get("server") # TODO: add in OAuth stuff. } return config def call(self, url, method_name, data=None): log.info("Deprecated, please use curling: %s, %s" % (url, method_name)) if data and method_name.lower() == "get": raise TypeError("You cannot use data in a GET request. " "Maybe you meant to use filters=...") data = json.dumps(data, cls=self.encoder or Encoder) if data else json.dumps({}) method = getattr(requests, method_name) try: with statsd.timer("solitude.call.%s" % method_name): result = method( url, data=data, headers={"content-type": "application/json"}, timeout=self.config.get("timeout", 10) ) except requests.ConnectionError: log.error("Solitude not accessible") raise SolitudeOffline(general_error) except requests.Timeout: log.error("Solitude timed out, limit %s" % self.config.get("timeout", 10)) raise SolitudeTimeout(general_error) if result.status_code in (200, 201, 202, 204): return json.loads(result.text) if result.text else {} else: log.error("Solitude error with %s: %r" % (url, result.text)) res = {} try: res = json.loads(result.text) if result.text else {} except: # Not a JSON error. pass code = res.get("error_code", 0) raise SolitudeError(lookup(code, res.get("error_data", {})), code=code) def upsert(self, method, params, lookup_by): """Shortcut function for calling get_<method> and subsequently calling post_<method> if there are no results. The values passed to the data param of get_<method> are the keys defined in the sequence `lookup_by`. """ lookup_data = dict((k, v) for k, v in params.items() if k in lookup_by) existing = self.__getattr__("get_%s" % method)(filters=lookup_data) if existing["meta"]["total_count"]: return existing["objects"][0] return self.__getattr__("post_%s" % method)(data=params) def __getattr__(self, attr): try: method, action = attr.split("_", 1) except: raise AttributeError(attr) target = mapping.get(action) if not target: raise AttributeError(attr) if method not in target[2]: raise AttributeError(attr) return partial(self.wrapped, **{"target": target, "method": method}) def wrapped(self, target=None, method=None, data=None, pk=None, filters=None): url = self._url(*target[:2], pk=pk) if filters: url = "%s?%s" % (url, self.filter_encoder(filters)) return self.call(url, method, data=data)
def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.slumber._add_callback({'method': add_transaction_id}) self.api = self.slumber.api.v1
def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get('key'), oauth.get('secret')) self.api = self.slumber.api.v1
def _tier(server, tier): srv = API(servers[server]) srv.activate_oauth(session['oauth']['key'], session['oauth']['secret']) return srv.by_url('/api/v1/services/price-currency/{0}/'.format(tier), parser=safe_parser)
class Client(object): def __init__(self, config=None): self.config = self.parse(config) self.api = API(config['server']) self.api.activate_oauth(settings.SOLITUDE_OAUTH.get('key'), settings.SOLITUDE_OAUTH.get('secret')) self.encoder = None self.filter_encoder = urllib.urlencode def call_uri(self, uri, method='get', data=None): """If you were given a URI by Solitude, pass it here and get that the value back. Since the URLs are relative, they couldn't simply be passed to `call()`. This handles all the prefixing and whatnot. """ uri = uri.lstrip('/') return self.call('%s/%s' % (self.config['server'], uri), method, data) def _url(self, context, name, pk=None): url = '%s/%s/%s/' % (self.config['server'], context, name) if pk: url = '%s%s/' % (url, pk) return url def parse(self, config=None): config = { 'server': config.get('server') # TODO: add in OAuth stuff. } return config def call(self, url, method_name, data=None): log.info('Deprecated, please use curling: %s, %s' % (url, method_name)) if data and method_name.lower() == 'get': raise TypeError('You cannot use data in a GET request. ' 'Maybe you meant to use filters=...') data = (json.dumps(data, cls=self.encoder or Encoder) if data else json.dumps({})) method = getattr(requests, method_name) try: with statsd.timer('solitude.call.%s' % method_name): result = method(url, data=data, headers={'content-type': 'application/json'}, timeout=self.config.get('timeout', 10)) except requests.ConnectionError: log.error('Solitude not accessible') raise SolitudeOffline(general_error) except requests.Timeout: log.error('Solitude timed out, limit %s' % self.config.get('timeout', 10)) raise SolitudeTimeout(general_error) if result.status_code in (200, 201, 202, 204): return json.loads(result.text) if result.text else {} else: log.error('Solitude error with %s: %r' % (url, result.text)) res = {} try: res = json.loads(result.text) if result.text else {} except: # Not a JSON error. pass code = res.get('error_code', 0) raise SolitudeError(lookup(code, res.get('error_data', {})), code=code) def upsert(self, method, params, lookup_by): """Shortcut function for calling get_<method> and subsequently calling post_<method> if there are no results. The values passed to the data param of get_<method> are the keys defined in the sequence `lookup_by`. """ lookup_data = dict((k, v) for k, v in params.items() if k in lookup_by) existing = self.__getattr__('get_%s' % method)(filters=lookup_data) if existing['meta']['total_count']: return existing['objects'][0] return self.__getattr__('post_%s' % method)(data=params) def __getattr__(self, attr): try: method, action = attr.split('_', 1) except: raise AttributeError(attr) target = mapping.get(action) if not target: raise AttributeError(attr) if method not in target[2]: raise AttributeError(attr) return partial(self.wrapped, **{'target': target, 'method': method}) def wrapped(self, target=None, method=None, data=None, pk=None, filters=None): url = self._url(*target[:2], pk=pk) if filters: url = '%s?%s' % (url, self.filter_encoder(filters)) return self.call(url, method, data=data)
def __init__(self, url, oauth): self.slumber = API(url) self.slumber.activate_oauth(oauth.get("key"), oauth.get("secret")) self.slumber._add_callback({"method": add_transaction_id}) self.api = self.slumber.api.v1