add cacheability
This commit is contained in:
parent
7e23c2a57f
commit
28e932832e
@ -46,11 +46,13 @@ class ApiKeyAuth( requests.auth.AuthBase ):
|
|||||||
return r
|
return r
|
||||||
|
|
||||||
class APIv2( object ):
|
class APIv2( object ):
|
||||||
def __init__( self, api_username, api_key, base = "https://fulcrm.org", api_path = "/api/v2" ):
|
def __init__( self, api_username, api_key, base = "https://fulcrm.org", api_path = "/api/v2", cache = None, cache_timeout = None ):
|
||||||
self.api_username = api_username
|
self.api_username = api_username
|
||||||
self.api_key = api_key
|
self.api_key = api_key
|
||||||
self.api_path = api_path
|
self.api_path = api_path
|
||||||
self.base = base
|
self.base = base
|
||||||
|
self.cache = cache
|
||||||
|
self.cache_timeout = cache_timeout
|
||||||
self.auth = ApiKeyAuth( self.api_username, self.api_key )
|
self.auth = ApiKeyAuth( self.api_username, self.api_key )
|
||||||
|
|
||||||
def normalize_path( self, path ):
|
def normalize_path( self, path ):
|
||||||
@ -140,6 +142,14 @@ class APIv2( object ):
|
|||||||
'DELETE': requests.delete
|
'DELETE': requests.delete
|
||||||
}.get( method, requests.get )
|
}.get( method, requests.get )
|
||||||
|
|
||||||
|
if self.cache and method is requests.get and not data:
|
||||||
|
rval = self.cache.get( url )
|
||||||
|
if rval is not None:
|
||||||
|
print( "CACHED", url )
|
||||||
|
return response_to_objdicts( rval )
|
||||||
|
else:
|
||||||
|
print( "NOCACHE", url )
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if data:
|
if data:
|
||||||
request = method( url, data = json.dumps( data ), auth = self.auth, timeout = 30.0 )
|
request = method( url, data = json.dumps( data ), auth = self.auth, timeout = 30.0 )
|
||||||
@ -153,7 +163,12 @@ class APIv2( object ):
|
|||||||
raise
|
raise
|
||||||
if request.ok:
|
if request.ok:
|
||||||
try:
|
try:
|
||||||
return response_to_objdicts( request.json() )
|
if self.cache and self.cache_timeout and method is requests.get and not data:
|
||||||
|
rval = request.json()
|
||||||
|
self.cache.set( url, rval, timeout = self.cache_timeout )
|
||||||
|
return response_to_objdicts( rval )
|
||||||
|
else:
|
||||||
|
return response_to_objdicts( request.json() )
|
||||||
except:
|
except:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user