Commits

Ben Bangert committed ab61d99

Various PEP 8 cleanups

Comments (0)

Files changed (5)

+"""Cache object
+
+The Cache object is used to manage a set of cache files and their
+associated backend. The backends can be rotated on the fly by
+specifying an alternate type when used.
+
+"""
 import beaker.container as container
 from beaker.exceptions import InvalidCacheBackendError
 import beaker.util as util
 
+
 clsmap = {
           'memory':container.MemoryNamespaceManager,
           'dbm':container.DBMNamespaceManager,
 except (InvalidCacheBackendError, SyntaxError):
     pass
 
+
 class Cache(object):
     """Front-end to the containment API implementing a data cache."""
     def __init__(self, namespace, **kwargs):
     def __setitem__(self, key, value):
         self.put(key, value)
 
+
 class CacheManager(object):
     def __init__(self, **kwargs):
         self.kwargs = kwargs

beaker/container.py

+"""Container and Namespace classes"""
 import anydbm
 import cPickle
 import logging
 import os.path
 import time
 
-from beaker.exceptions import MissingCacheParameter
 import beaker.util as util
-from beaker.synchronization import _threading, file_synchronizer, mutex_synchronizer, NameLock
+from beaker.exceptions import CreationAbortedError, MissingCacheParameter
+from beaker.synchronization import _threading, file_synchronizer, \
+     mutex_synchronizer, NameLock
 
 __all__ = ['ContainerContext', 'Value', 'Container', 
            'MemoryContainer', 'DBMContainer', 'NamespaceManager',
            'MemoryNamespaceManager', 'DBMNamespaceManager', 'FileContainer',
            'FileNamespaceManager', 'CreationAbortedError']
 
+
 logger = logging.getLogger('beaker.container')
 if logger.isEnabledFor(logging.DEBUG):
     debug = logger.debug
 else:
-    def debug(message):
+    def debug(message, *args):
         pass
-     
+
+
 class NamespaceManager(object):
-    """handles dictionary operations and locking for a namespace of values.  
+    """Handles dictionary operations and locking for a namespace of
+    values.
     
-    the implementation for setting and retrieving the namespace data is handled
-    by subclasses.
+    The implementation for setting and retrieving the namespace data is
+    handled by subclasses.
     
     NamespaceManager may be used alone, or may be privately accessed by
-    one or more Container objects.  Container objects provide per-key services
-    like expiration times and automatic recreation of values.  
+    one or more Container objects.  Container objects provide per-key
+    services like expiration times and automatic recreation of values.
     
-    multiple NamespaceManagers created with a particular name will all share
-    access to the same underlying datasource and will attempt to synchronize
-    against a common mutex object.  The scope of this sharing may be within 
-    a single process or across multiple processes, depending on the type of
-    NamespaceManager used.
+    Multiple NamespaceManagers created with a particular name will all
+    share access to the same underlying datasource and will attempt to
+    synchronize against a common mutex object.  The scope of this
+    sharing may be within a single process or across multiple
+    processes, depending on the type of NamespaceManager used.
     
-    The NamespaceManager itself is generally threadsafe, except in the case
-    of the DBMNamespaceManager in conjunction with the gdbm dbm implementation.
+    The NamespaceManager itself is generally threadsafe, except in the
+    case of the DBMNamespaceManager in conjunction with the gdbm dbm
+    implementation.
 
     """
     def __init__(self, namespace):
         finally:
             self.access_lock.release_write_lock()
 
+
 class ContainerContext(object):
-    """initial context supplied to Containers. 
-    
-    Keeps track of namespacemangers keyed off of namespace names and container types.
+    """Initial context supplied to Containers. 
+
+    Keeps track of namespacemangers keyed off of namespace names and
+    container types.
 
     """
     def __init__(self):
     def clear(self):
         self.registry.clear()
 
+
 class Value(object):
-    __slots__ = 'key', 'createfunc', 'expiretime', 'starttime', 'storedtime', 'namespacemanager'
+    __slots__ = 'key', 'createfunc', 'expiretime', 'starttime', 'storedtime',\
+                'namespacemanager'
 
-    def __init__(self, key, context, namespace, nscls, createfunc=None, expiretime=None, starttime=None, **kwargs):
+    def __init__(self, key, context, namespace, nscls, createfunc=None,
+                 expiretime=None, starttime=None, **kwargs):
         self.key = key
         self.createfunc = createfunc
         self.expiretime = expiretime
         self.starttime = starttime
         self.storedtime = -1
-        self.namespacemanager = context.get_namespace(namespace, nscls, **kwargs)
+        self.namespacemanager = context.get_namespace(namespace, nscls,
+                                                      **kwargs)
 
     def has_value(self):
         """return true if the container has a value stored.
         self.namespacemanager.acquire_write_lock()
         try:
             self.storedtime = time.time()
-            debug("set_value stored time %d" % self.storedtime)
+            debug("set_value stored time %d", self.storedtime)
             self.namespacemanager[self.key] = [self.storedtime, value]
         finally:
             self.namespacemanager.release_write_lock()
         finally:
             self.namespacemanager.release_write_lock()
 
-class CreationAbortedError(Exception):
-    """an exception that allows a creation function to abort what it's doing"""
 
 class MemoryNamespaceManager(NamespaceManager):
     namespaces = util.SyncDict()
 
     def __init__(self, namespace, **kwargs):
         NamespaceManager.__init__(self, namespace)
-        self.dictionary = MemoryNamespaceManager.namespaces.get(self.namespace, dict)
+        self.dictionary = MemoryNamespaceManager.namespaces.get(self.namespace,
+                                                                dict)
     
     def get_access_lock(self):
         return mutex_synchronizer(
         
     def get_creation_lock(self, key):
         return NameLock(
-            identifier="memorycontainer/funclock/%s/%s" % (self.namespace, key), 
+            identifier="memorycontainer/funclock/%s/%s" % (self.namespace, key),
             reentrant=True
         )
         
     def keys(self):
         return self.dictionary.keys()
 
+
 class DBMNamespaceManager(NamespaceManager):
-
     def __init__(self, namespace, dbmmodule=None, data_dir=None, 
             dbm_dir=None, lock_dir=None, digest_filenames=True, **kwargs):
         self.digest_filenames = digest_filenames
         self.dbm = None
         NamespaceManager.__init__(self, namespace)
 
-        self.file = util.encoded_path(root= self.dbm_dir, 
-                                      identifiers=[self.namespace], extension='.dbm', digest_filenames=self.digest_filenames)
+        self.file = util.encoded_path(root= self.dbm_dir,
+                                      identifiers=[self.namespace],
+                                      extension='.dbm',
+                                      digest_filenames=self.digest_filenames)
         
-        debug("data file %s" % self.file)
-        
+        debug("data file %s", self.file)
         self._checkfile()
 
     def get_access_lock(self):
-        return file_synchronizer(identifier=self.namespace, lock_dir=self.lock_dir)
+        return file_synchronizer(identifier=self.namespace,
+                                 lock_dir=self.lock_dir)
                                  
     def get_creation_lock(self, key):
         return file_synchronizer(
         return list
 
     def do_open(self, flags):
-        debug("opening dbm file %s" % self.file)
+        debug("opening dbm file %s", self.file)
         try:
             self.dbm = self.dbmmodule.open(self.file, flags)
         except:
 
     def do_close(self):
         if self.dbm is not None:
-            debug("closing dbm file %s" % self.file)
+            debug("closing dbm file %s", self.file)
             self.dbm.close()
         
     def do_remove(self):
     def keys(self):
         return self.dbm.keys()
 
+
 class FileNamespaceManager(NamespaceManager):
-
-    def __init__(self, namespace, data_dir=None, file_dir=None, lock_dir=None, digest_filenames=True, **kwargs):
+    def __init__(self, namespace, data_dir=None, file_dir=None, lock_dir=None,
+                 digest_filenames=True, **kwargs):
         self.digest_filenames = digest_filenames
         
         if not file_dir and not data_dir:
 
         self.file = util.encoded_path(root=self.file_dir, 
                                       identifiers=[self.namespace],
-                                      extension='.cache',digest_filenames=self.digest_filenames)
+                                      extension='.cache',
+                                      digest_filenames=self.digest_filenames)
         self.hash = {}
         
-        debug("data file %s" % self.file)
+        debug("data file %s", self.file)
 
     def get_access_lock(self):
-        return file_synchronizer(identifier=self.namespace, lock_dir=self.lock_dir)
+        return file_synchronizer(identifier=self.namespace,
+                                 lock_dir=self.lock_dir)
                                  
     def get_creation_lock(self, key):
         return file_synchronizer(
     def __init__(cls, classname, bases, dict_):
         namespace_classes[cls] = cls.namespace_class
         return type.__init__(cls, classname, bases, dict_)
-    def __call__(self, key, context, namespace, createfunc=None, expiretime=None, starttime=None, **kwargs):
+    def __call__(self, key, context, namespace, createfunc=None,
+                 expiretime=None, starttime=None, **kwargs):
         nscls = namespace_classes[self]
-        return Value(key, context, namespace, nscls, createfunc=createfunc, expiretime=expiretime, starttime=starttime, **kwargs)
+        return Value(key, context, namespace, nscls, createfunc=createfunc,
+                     expiretime=expiretime, starttime=starttime, **kwargs)
 
 class Container(object):
     __metaclass__ = ContainerMeta

beaker/docs/index.rst

 * :ref:`genindex`
 * :ref:`modindex`
 * :ref:`search`
-

beaker/exceptions.py

+"""Beaker exception classes"""
+
 class BeakerException(Exception):
     pass
 
+
+class CreationAbortedError(Exception):
+    """an exception that allows a creation function to abort what it's
+    doing"""
+
+
 class InvalidCacheBackendError(BeakerException):
     pass
 
+
 class MissingCacheParameter(BeakerException):
     pass
 
+
 class LockError(BeakerException):
     pass

beaker/middleware.py

 from beaker.session import Session, SessionObject
 from beaker.util import coerce_cache_params, coerce_session_params
 
+
 class CacheMiddleware(object):
     cache = beaker_cache
     
     def __init__(self, app, config=None, environ_key='beaker.cache', **kwargs):
         """Initialize the Cache Middleware
         
-        The Cache middleware will make a Cache instance available every request
-        under the ``environ['beaker.cache']`` key by default. The location in
-        environ can be changed by setting ``environ_key``.
+        The Cache middleware will make a Cache instance available
+        every request under the ``environ['beaker.cache']`` key by
+        default. The location in environ can be changed by setting
+        ``environ_key``.
         
         ``config``
-            dict  All settings should be prefixed by 'cache.'. This method of
-            passing variables is intended for Paste and other setups that
-            accumulate multiple component settings in a single dictionary. If
-            config contains *no cache. prefixed args*, then *all* of the config
-            options will be used to intialize the Cache objects.
+            dict  All settings should be prefixed by 'cache.'. This
+            method of passing variables is intended for Paste and other
+            setups that accumulate multiple component settings in a
+            single dictionary. If config contains *no cache. prefixed
+            args*, then *all* of the config options will be used to
+            intialize the Cache objects.
         
         ``environ_key``
-            Location where the Cache instance will keyed in the WSGI environ
+            Location where the Cache instance will keyed in the WSGI
+            environ
         
         ``**kwargs``
-            All keyword arguments are assumed to be cache settings and will
-            override any settings found in ``config``
+            All keyword arguments are assumed to be cache settings and
+            will override any settings found in ``config``
+
         """
         self.app = app
         config = config or {}
         # Coerce and validate cache params
         coerce_cache_params(self.options)
         
-        # Assume all keys are intended for cache if none are prefixed with 'cache.'
+        # Assume all keys are intended for cache if none are prefixed with
+        # 'cache.'
         if not self.options and config:
             self.options = config
         
     def __call__(self, environ, start_response):
         if environ.get('paste.registry'):
             if environ['paste.registry'].reglist:
-                environ['paste.registry'].register(self.cache, self.cache_manager)
+                environ['paste.registry'].register(self.cache,
+                                                   self.cache_manager)
         environ[self.environ_key] = self.cache_manager
         return self.app(environ, start_response)
 
 class SessionMiddleware(object):
     session = beaker_session
     
-    def __init__(self, wrap_app, config=None, environ_key='beaker.session', **kwargs):
+    def __init__(self, wrap_app, config=None, environ_key='beaker.session',
+                 **kwargs):
         """Initialize the Session Middleware
         
-        The Session middleware will make a lazy session instance available
-        every request under the ``environ['beaker.session']`` key by
-        default. The location in environ can be changed by setting
-        ``environ_key``.
+        The Session middleware will make a lazy session instance
+        available every request under the ``environ['beaker.session']``
+        key by default. The location in environ can be changed by
+        setting ``environ_key``.
         
         ``config``
-            dict  All settings should be prefixed by 'session.'. This method of
-            passing variables is intended for Paste and other setups that
-            accumulate multiple component settings in a single dictionary. If
-            config contains *no cache. prefixed args*, then *all* of the config
-            options will be used to intialize the Cache objects.
+            dict  All settings should be prefixed by 'session.'. This
+            method of passing variables is intended for Paste and other
+            setups that accumulate multiple component settings in a
+            single dictionary. If config contains *no cache. prefixed
+            args*, then *all* of the config options will be used to
+            intialize the Cache objects.
         
         ``environ_key``
-            Location where the Session instance will keyed in the WSGI environ
+            Location where the Session instance will keyed in the WSGI
+            environ
         
         ``**kwargs``
-            All keyword arguments are assumed to be cache settings and will
-            override any settings found in ``config``
+            All keyword arguments are assumed to be cache settings and
+            will override any settings found in ``config``
+
         """
         config = config or {}
         
         # Coerce and validate session params
         coerce_session_params(self.options)
         
-        # Assume all keys are intended for cache if none are prefixed with 'cache.'
+        # Assume all keys are intended for cache if none are prefixed with
+        # 'cache.'
         if not self.options and config:
             self.options = config