Commits

Andriy Kornatskyy committed b716a5a

Added ability to specify time as int or timedelta.

Comments (0)

Files changed (3)

src/wheezy/caching/dependency.py

 
 from wheezy.caching.comp import itervalues
 from wheezy.caching.comp import xrange
+from wheezy.caching.utils import total_seconds
 
 
 class CacheDependency(object):
            *namespace* - a default namespace.
         """
         self.cache = cache
-        self.time = time
+        self.time = total_seconds(time)
         self.namespace = namespace
 
     def next_key(self, master_key):

src/wheezy/caching/patterns.py

 from time import time
 
 from wheezy.caching.dependency import CacheDependency
+from wheezy.caching.utils import total_seconds
 
 
 class Cached(object):
                  timeout=10, key_prefix='one_pass:'):
         self.cache = cache
         self.key_builder = key_builder
-        self.time = time
+        self.time = total_seconds(time)
         self.namespace = namespace
-        self.timeout = timeout
+        self.timeout = total_seconds(timeout)
         self.key_prefix = key_prefix
         self.dependency = CacheDependency(cache, time, namespace)
 
     def __init__(self, cache, key, time=10, namespace=None):
         self.cache = cache
         self.key = key
-        self.time = time
+        self.time = total_seconds(time)
         self.namespace = namespace
         self.acquired = False
 
     return '%s-%s%s' % (key_prefix, func.__name__, ':%r' * n)
 
 
-def key_formater(key_prefix):
+def key_formatter(key_prefix):
     """ Specialize a key format with *key_prefix*.
 
         >>> def list_items(self, locale='en', sort_order=1):
         ...     pass
-        >>> repo_key_format = key_formater('repo')
+        >>> repo_key_format = key_formatter('repo')
         >>> repo_key_format(list_items)
         'repo-list_items:%r:%r'
     """

src/wheezy/caching/utils.py

+
+from datetime import timedelta
+
+
+def total_seconds(delta):
+    """ Returns a total number of seconds for the given delta.
+
+        ``delta`` can be ``datetime.timedelta``.
+
+        >>> total_seconds(timedelta(hours=2))
+        7200
+
+        or int:
+
+        >>> total_seconds(100)
+        100
+
+        otherwise raise ``TypeError``.
+
+        >>> total_seconds('100') # doctest: +ELLIPSIS
+        Traceback (most recent call last):
+            ...
+        TypeError: ...
+    """
+    if isinstance(delta, int):
+        return delta
+    elif isinstance(delta, timedelta):
+        return delta.seconds + delta.days * 86400
+    else:
+        raise TypeError('Expecting type datetime.timedelta '
+                        'or int for seconds')