From 474699f1317e7ac79e9a3cf9638db296368b9bb0 Mon Sep 17 00:00:00 2001 From: Josh Roesslein Date: Thu, 30 Jul 2009 02:44:34 -0500 Subject: [PATCH] Allow for customized timeouts for bindings. --- tweepy/binder.py | 7 ++++--- tweepy/cache.py | 20 ++++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/tweepy/binder.py b/tweepy/binder.py index 48addde..78aaa23 100644 --- a/tweepy/binder.py +++ b/tweepy/binder.py @@ -8,7 +8,8 @@ import urllib from parsers import parse_error from error import TweepError -def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, host=None): +def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, + timeout=None, host=None): def _call(api, *args, **kargs): # If require auth, throw exception if credentials not provided @@ -29,10 +30,10 @@ def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, # Check cache if caching enabled and method is GET if api.cache and method == 'GET': - cache_result = api.cache.get(url) + cache_result = api.cache.get(url, timeout) if cache_result: # if cache result found and not expired, return it - print 'hit!' + print 'hit!!!!' return cache_result # Open connection diff --git a/tweepy/cache.py b/tweepy/cache.py index bc6b11f..1e1b37e 100644 --- a/tweepy/cache.py +++ b/tweepy/cache.py @@ -21,9 +21,10 @@ class Cache(object): """ raise NotImplemented - def get(self, key): + def get(self, key, timeout=None): """Get cached entry if exists and not expired key: which entry to get + timeout: override timeout with this value [optional] """ raise NotImplemented @@ -43,14 +44,14 @@ class MemoryCache(Cache): self._entries = {} self.lock = threading.Lock() - def _is_expired(self, entry): - return (time.time() - entry[0]) >= self.timeout + def _is_expired(self, entry, timeout): + return timeout > 0 and (time.time() - entry[0]) >= timeout def store(self, key, value): with self.lock: self._entries[key] = (time.time(), value) - def get(self, key): + def get(self, key, timeout=None): with self.lock: # check to see if we have this key entry = self._entries.get(key) @@ -58,8 +59,15 @@ class MemoryCache(Cache): # no hit, return nothing return None + # use provided timeout in arguments if provided + # otherwise use the one provided during init. + if timeout is None: + _timeout = self.timeout + else: + _timeout = timeout + # make sure entry is not expired - if self._is_expired(entry): + if self._is_expired(entry, _timeout): # entry expired, delete and return nothing del self._entries[key] return None @@ -70,7 +78,7 @@ class MemoryCache(Cache): def cleanup(self): with self.lock: for k,v in self._entries.items(): - if self._is_expired(v): + if self._is_expired(v, self.timeout): del self._entries[k] def flush(self): -- 2.25.1