def delete(self, resource): logger.debug('Deleting resource %s', resource) res = self._session.delete(resource) if res.status_code != 200: raise APIException(resource, res.status_code, res.json()) return {}
def post(self, resource, data={}): logger.debug('Posting resource %s (data=%s)', resource, data) res = self._session.post(resource, data=data) if res.status_code not in [200, 201]: raise APIException(resource, res.status_code, res.json()) return {}
def put(self, resource, data={}): logger.debug('Putting resource %s (data=%s)', resource, data) res = self._session.put(resource, data=data) if res.status_code != 200: raise APIException(resource, res.status_code, res.json()) return {}
def test_apiexception_str_message(self): e = APIException('http://example.com', 205, {'message': 'example error'}) self.assertIn('example error', str(e)) self.assertIn('205', str(e))
def test_apiexception_data(self): e = APIException('http://example.com', 205, {'message': 'example error'}) self.assertEqual(e.url, 'http://example.com') self.assertEqual(e.status_code, 205)
def _authorize(self, params): auth = text_( base64.b64encode(bytes_("%s:%s" % (self.client_id, self.api_key)))) headers = {"Authorization": "Basic %s" % auth} resource = "%s/token" % self._oauth_endpoint res = self._session.post(resource, params=params, headers=headers) if res.status_code != 200: raise APIException(resource, res.status_code, res.json()) return res.json()
def _authorize(self, params): auth = text_( base64.b64encode(bytes_("%s:%s" % (self.client_id, self.api_key)))) headers = {"Authorization": "Basic %s" % auth} res = self._session.post("%s/token" % self._oauth_endpoint, params=params, headers=headers) if res.status_code != 200: raise APIException("Got unexpected status code from API: %i" % res.status_code) return res.json()
def get(self, resource, params=None): headers = {"User-Agent": self._useragent, "Accept": "application/json"} headers.update(self._headers) logger.debug('Getting resource %s', resource) res = requests.get(resource, headers=headers, params=params if params else {}) if res.status_code != 200: raise APIException("Got unexpected status code from server: %i" % res.status_code) return res.json()
def get(self, resource, params=None): logger.debug('Getting resource %s', resource) if params is None: params = {} # remove params from resource URI (needed for paginated stuff) parsed_uri = urlparse(resource) qs = parsed_uri.query resource = urlunparse(parsed_uri._replace(query='')) prms = {} for tup in parse_qsl(qs): prms[tup[0]] = tup[1] # params supplied to self.get() override parsed params for key in params: prms[key] = params[key] # check cache key = (resource, frozenset(self._session.headers.items()), frozenset(prms.items())) cached = self.cache.get(key) if cached and cached['expires'] > time.time(): logger.debug('Cache hit for resource %s (params=%s)', resource, prms) return cached['payload'] elif cached: logger.debug('Cache stale for resource %s (params=%s)', resource, prms) self.cache.invalidate(key) else: logger.debug('Cache miss for resource %s (params=%s', resource, prms) logger.debug('Getting resource %s (params=%s)', resource, prms) res = self._session.get(resource, params=prms) if res.status_code != 200: raise APIException("Got unexpected status code from server: %i" % res.status_code) ret = res.json() # cache result key = (resource, frozenset(self._session.headers.items()), frozenset(prms.items())) expires = self._get_expires(res) if expires > 0: self.cache.put(key, { 'expires': time.time() + expires, 'payload': ret }) return ret
def get(self, resource, params={}, caching=True): logger.debug('Getting resource %s', resource) resource, prms = self._parse_parameters(resource, params) # check cache key = ( resource, frozenset( self._session.headers.items()), frozenset( prms.items())) cached = self.cache.get(key) if cached and cached['expires'] > time.time(): logger.debug( 'Cache hit for resource %s (params=%s)', resource, prms) return cached['payload'] elif cached: logger.debug( 'Cache stale for resource %s (params=%s)', resource, prms) self.cache.invalidate(key) else: logger.debug( 'Cache miss for resource %s (params=%s', resource, prms) logger.debug('Getting resource %s (params=%s)', resource, prms) res = self._session.get(resource, params=prms) if res.status_code != 200: raise APIException( resource, res.status_code, res.json() ) ret = res.json() # cache result only if caching = True (default) key = ( resource, frozenset( self._session.headers.items()), frozenset( prms.items())) expires = self._get_expires(res) if expires > 0 and caching: self.cache.put( key, { 'expires': time.time() + expires, 'payload': ret}) return ret
def authorize(self, code): auth = text_( base64.b64encode(bytes_("%s:%s" % (self.client_id, self.api_key)))) headers = {"Authorization": "Basic %s" % auth} params = {"grant_type": "authorization_code", "code": code} res = requests.post("%s/token" % self._oauth_endpoint, params=params, headers=headers) if res.status_code != 200: raise APIException("Got unexpected status code from API: %i" % res.status_code) return AuthedConnection(res.json(), self._authed_endpoint, self._oauth_endpoint, self.client_id, self.api_key)
def test_apiexception_str_no_message(self): e = APIException('http://example.com', 205, {'exception_type': 'wierd'}) self.assertIn('205', str(e))
def get(self, resource, params=None): logger.debug('Getting resource %s', resource) if params is None: params = {} # remove params from resource URI (needed for paginated stuff) parsed_uri = urlparse(resource) qs = parsed_uri.query resource = urlunparse(parsed_uri._replace(query='')) prms = {} for tup in parse_qsl(qs): prms[tup[0]] = tup[1] # params supplied to self.get() override parsed params for key in params: prms[key] = params[key] # check cache ''' TODO: check how to differentiate between clients. Current cache control does now work if auth token is updated. Going on a limb here and assuming the secret key will be the equivalent of current api key, named as api_key in pycrest implementation ''' key = frozenset({ 'resource': resource, 'key': self.client_id }.items()).union(prms.items()) cached = self.cache.get(key) if cached and cached['expires'] > time.time(): logger.debug('Cache hit for resource %s (params=%s)', resource, prms) return cached['payload'] elif cached: logger.debug('Cache stale for resource %s (params=%s)', resource, prms) self.cache.invalidate(key) else: logger.debug('Cache miss for resource %s (params=%s)', resource, prms) logger.debug('Getting resource %s (params=%s)', resource, prms) #limit the requests per second after cache check. self._requests_limiter.sleep() res = self._session.get(resource, params=prms) if res.status_code != 200: raise APIException( "Got unexpected status code from server: %i (%s)" % (res.status_code, res.reason)) ret = res.json() # cache result key = frozenset({ 'resource': resource, 'key': self.client_id }.items()).union(prms.items()) expires = self._get_expires(res) if expires > 0: self.cache.put(key, { 'expires': time.time() + expires, 'payload': ret }) return ret