error handling and timeouts

master
Marek Isalski 7 years ago
parent ece9a3e86a
commit b469be7dbb

@ -29,6 +29,8 @@ class APIv2( object ):
if not path.startswith( "/" ): if not path.startswith( "/" ):
path = "/" + path path = "/" + path
path = self.api_path + path path = self.api_path + path
if not path.endswith( "/" ):
path = path + "/"
return path return path
def normalize_url( self, url, no_d = False, query = None ): def normalize_url( self, url, no_d = False, query = None ):
@ -58,6 +60,26 @@ class APIv2( object ):
new_url = urlqueryparse.set_query_fields( url, new_query ) new_url = urlqueryparse.set_query_fields( url, new_query )
return new_url return new_url
def get( self, url, query = None, _countdown = 5 ):
url = self.normalize_url( url, query = query )
return self.make_request( url, data = None, method = 'GET', _countdown = _countdown )
def post( self, url, data, query = None, _countdown = 5 ):
url = self.normalize_url( url, query = query )
return self.make_request( url, data = data, method = 'POST', _countdown = _countdown )
def patch( self, url, data, query = None, _countdown = 5 ):
url = self.normalize_url( url, query = query )
return self.make_request( url, data = data, method = 'PATCH', _countdown = _countdown )
def put( self, url, data, query = None, _countdown = 5 ):
url = self.normalize_url( url, query = query )
return self.make_request( url, data = data, method = 'PUT', _countdown = _countdown )
def delete( self, url, query = None, _countdown = 5 ):
url = self.normalize_url( url, query = query )
return self.make_request( url, data = None, method = 'DELETE', _countdown = _countdown )
def make_request( self, url, data, method, _countdown = 5 ): def make_request( self, url, data, method, _countdown = 5 ):
method = { 'POST': requests.post, method = { 'POST': requests.post,
'PATCH': requests.patch, 'PATCH': requests.patch,
@ -67,9 +89,9 @@ class APIv2( object ):
try: try:
if data: if data:
request = method( url, data = json.dumps( data ), auth = self.auth ) request = method( url, data = json.dumps( data ), auth = self.auth, timeout = 10.0 )
else: else:
request = method( url, auth = self.auth ) request = method( url, auth = self.auth, timeout = 10.0 )
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
if _countdown > 0: if _countdown > 0:
time.sleep( 2 ** ( 5 - _countdown ) ) time.sleep( 2 ** ( 5 - _countdown ) )
@ -82,7 +104,7 @@ class APIv2( object ):
except: except:
return None return None
else: else:
raise ValueError( request.text ) request.raise_for_status()
def get_one( self, url, no_d = False, query = None ): def get_one( self, url, no_d = False, query = None ):
url = self.normalize_url( url, no_d = no_d, query = query ) url = self.normalize_url( url, no_d = no_d, query = query )

Loading…
Cancel
Save