add objdict functionality

master
Marek Isalski 3 years ago
parent 8076861a34
commit 7e23c2a57f

@ -8,6 +8,32 @@ path_to_pk = re.compile( r".*/([0-9]+)/(\?.*)?(#.*)?" )
from . import urlqueryparse from . import urlqueryparse
class objdict( dict ):
@classmethod
def response_to_objdicts( cls, i ):
if isinstance( i, dict ):
return cls( i )
elif isinstance( i, ( list, tuple ) ):
return [ cls.response_to_objdicts( v ) for v in i ]
return i
def __getattr__( self, name ):
if name in self:
return self.__class__.response_to_objdicts( self[ name ] )
else:
raise AttributeError( "No such attribute: " + name )
def __setattr__( self, name, value ):
self[ name ] = value
def __delattr__( self, name ):
if name in self:
del self[ name ]
else:
raise AttributeError( "No such attribute: " + name )
response_to_objdicts = objdict.response_to_objdicts
class ApiKeyAuth( requests.auth.AuthBase ): class ApiKeyAuth( requests.auth.AuthBase ):
def __init__( self, api_username, api_key ): def __init__( self, api_username, api_key ):
self.api_username = api_username self.api_username = api_username
@ -116,9 +142,9 @@ class APIv2( object ):
try: try:
if data: if data:
request = method( url, data = json.dumps( data ), auth = self.auth, timeout = 10.0 ) request = method( url, data = json.dumps( data ), auth = self.auth, timeout = 30.0 )
else: else:
request = method( url, auth = self.auth, timeout = 10.0 ) request = method( url, auth = self.auth, timeout = 30.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 ) )
@ -127,7 +153,7 @@ class APIv2( object ):
raise raise
if request.ok: if request.ok:
try: try:
return request.json() return response_to_objdicts( request.json() )
except: except:
return None return None
else: else:
@ -148,7 +174,7 @@ class APIv2( object ):
result = self.make_request( url, None, 'GET' ) result = self.make_request( url, None, 'GET' )
if 'results' in result: if 'results' in result:
for object in result[ 'results' ]: for object in result[ 'results' ]:
yield object yield response_to_objdicts( object )
if 'next' in result: if 'next' in result:
next = result.get( 'next', None ) next = result.get( 'next', None )
if next: if next:

Loading…
Cancel
Save