Commits

Ben Bangert committed f4cb70a

More PEP8 fixes, removed old cereal.

Comments (0)

Files changed (3)

beaker/session.py

 __all__ = ['SignedCookie', 'Session']
 
 class SignedCookie(Cookie.BaseCookie):
-    "extends python cookie to give digital signature support"
+    """Extends python cookie to give digital signature support"""
     def __init__(self, secret, input=None):
         self.secret = secret
         Cookie.BaseCookie.__init__(self, input)
 
 
 class Session(dict):
-    "session object that uses container package for storage"
-
+    """Session object that uses container package for storage"""
     def __init__(self, request, id=None, invalidate_corrupt=False,
                  use_cookies=True, type=None, data_dir=None,
                  key='beaker.session.id', timeout=None, cookie_expires=True,
         
     def _create_id(self):
         self.id = md5(
-            md5("%f%s%f%s" % (time.time(), id({}), random.random(), os.getpid()) ).hexdigest(), 
+            md5("%f%s%f%s" % (time.time(), id({}), random.random(),
+                              os.getpid()) ).hexdigest(), 
         ).hexdigest()
         self.is_new = True
         if self.use_cookies:
         self.request['set_cookie'] = True
 
     def invalidate(self):
-        "invalidates this session, creates a new session id, returns to the is_new state"
+        """Invalidates this session, creates a new session id, returns
+        to the is_new state"""
         if hasattr(self, 'namespace'):
             namespace = self.namespace
             namespace.acquire_write_lock()
         self.was_invalidated = True
         self._create_id()
         self.load()
-
-                    
+ 
     def load(self):
-        "loads the data from this session from persistent storage"
-
-        self.namespace = namespace = self.namespace_class(self.id, data_dir=self.data_dir,
-                                              digest_filenames=False, **self.namespace_args)
+        "Loads the data from this session from persistent storage"
+        self.namespace = namespace = self.namespace_class(self.id,
+            data_dir=self.data_dir, digest_filenames=False,
+            **self.namespace_args)
         
         self.request['set_cookie'] = True
         
             namespace.release_write_lock()
     
     def save(self):
-        "saves the data for this session to persistent storage"
-
+        "Saves the data for this session to persistent storage"
         if not hasattr(self, 'namespace'):
             self.namespace = self.namespace_class(
                                     self.id, 
             self.request['set_cookie'] = True
     
     def lock(self):
-        """locks this session against other processes/threads.  this is 
+        """Locks this session against other processes/threads.  This is
         automatic when load/save is called.
         
         ***use with caution*** and always with a corresponding 'unlock'
-        inside a "finally:" block,
-        as a stray lock typically cannot be unlocked
-        without shutting down the whole application.
+        inside a "finally:" block, as a stray lock typically cannot be
+        unlocked without shutting down the whole application.
+
         """
         self.namespace.acquire_write_lock()
 
     def unlock(self):
-        """unlocks this session against other processes/threads.  this is 
-        automatic when load/save is called.
+        """Unlocks this session against other processes/threads.  This
+        is automatic when load/save is called.
 
-        ***use with caution*** and always within a "finally:" block,
-        as a stray lock typically cannot be unlocked
-        without shutting down the whole application.
-        
+        ***use with caution*** and always within a "finally:" block, as
+        a stray lock typically cannot be unlocked without shutting down
+        the whole application.
+
         """
         self.namespace.release_write_lock()
 
         regardless of the cookie being present or not to determine
         whether session data is still valid.
     ``encrypt_key``
-        The key to use for the session encryption, if not provided the session
-        will not be encrypted.
+        The key to use for the session encryption, if not provided the
+        session will not be encrypted.
     ``validate_key``
         The key used to sign the encrypted session
     ``cookie_domain``
             cookieheader = ''
         
         if validate_key is None:
-            raise BeakerException("No validate_key specified for Cookie only Session.")
+            raise BeakerException("No validate_key specified for Cookie only "
+                                  "Session.")
         
         try:
             self.cookie = SignedCookie(validate_key, input=cookieheader)
                 self.update(self._decrypt_data())
             except:
                 pass
-            if self.timeout is not None and time.time() - self['_accessed_time'] > self.timeout:
+            if self.timeout is not None and time.time() - \
+               self['_accessed_time'] > self.timeout:
                 self.clear()
             self._create_cookie()
     
     id = property(id)
     
     def _encrypt_data(self):
-        """Cerealize, encipher, and base64 the session dict"""
+        """Serialize, encipher, and base64 the session dict"""
         if self.encrypt_key:
             nonce = b64encode(os.urandom(40))[:8]
-            encrypt_key = generateCryptoKeys(self.encrypt_key, self.validate_key + nonce, 1)
+            encrypt_key = generateCryptoKeys(self.encrypt_key,
+                                             self.validate_key + nonce, 1)
             ctrcipher = aes.AES(encrypt_key)
             data = cPickle.dumps(self.copy(), protocol=2)
             return nonce + b64encode(ctrcipher.process(data))
             return b64encode(data)
     
     def _decrypt_data(self):
-        """Bas64, decipher, then un-cerealize the data for the session dict"""
+        """Bas64, decipher, then un-serialize the data for the session
+        dict"""
         if self.encrypt_key:
             nonce = self.cookie[self.key].value[:8]
-            encrypt_key = generateCryptoKeys(self.encrypt_key, self.validate_key + nonce, 1)
+            encrypt_key = generateCryptoKeys(self.encrypt_key,
+                                             self.validate_key + nonce, 1)
             ctrcipher = aes.AES(encrypt_key)
             payload = b64decode(self.cookie[self.key].value[8:])
             data = ctrcipher.process(payload)
         ).hexdigest()
     
     def save(self):
-        "saves the data for this session to persistent storage"
+        """Saves the data for this session to persistent storage"""
         self._create_cookie()
     
     def _create_cookie(self):
 class SessionObject(object):
     """Session proxy/lazy creator
     
-    This object proxies access to the actual session object, so that in the
-    case that the session hasn't been used before, it will be setup. This
-    avoid creating and loading the session from persistent storage unless
-    its actually used during the request.
+    This object proxies access to the actual session object, so that in
+    the case that the session hasn't been used before, it will be
+    setup. This avoid creating and loading the session from persistent
+    storage unless its actually used during the request.
     
     """
     def __init__(self, environ, **params):
             if params.get('type') == 'cookie':
                 self.__dict__['_sess'] = CookieSession(req, **params)
             else:
-                self.__dict__['_sess'] = Session(req, use_cookies=True, **params)
+                self.__dict__['_sess'] = Session(req, use_cookies=True,
+                                                 **params)
         return self.__dict__['_sess']
     
     def __getattr__(self, attr):

beaker/synchronization.py

-__all__  = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer", "NameLock", "_threading"]
-
+"""Synchronization module for keeping state of values in sync"""
 import os
 import sys
 import tempfile
 from beaker import util
 from beaker.exceptions import LockError
 
+__all__  = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer",
+            "NameLock", "_threading"]
+
+
 class NameLock(object):
-    """a proxy for an RLock object that is stored in a name 
-    based registry.  
+    """a proxy for an RLock object that is stored in a name based
+    registry.  
     
-    Multiple threads can get a reference to the same RLock based on 
-    the name alone, and synchronize operations related to that name.
-    """
-     
+    Multiple threads can get a reference to the same RLock based on the
+    name alone, and synchronize operations related to that name.
+
+    """     
     locks = util.WeakValuedRegistry()
 
     class NLContainer(object):
         if identifier is None:
             self._lock = NameLock.NLContainer(reentrant)
         else:
-            self._lock = NameLock.locks.get(identifier, NameLock.NLContainer, reentrant)
+            self._lock = NameLock.locks.get(identifier, NameLock.NLContainer,
+                                            reentrant)
 
     def acquire(self, wait = True):
         return self._lock().acquire(wait)
     def release(self):
         self._lock().release()
 
+
 _synchronizers = util.WeakValuedRegistry()
 def _synchronizer(identifier, cls, **kwargs):
     return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
 
+
 def file_synchronizer(identifier, **kwargs):
     if not has_flock:
         return mutex_synchronizer(identifier)
     else:
         return _synchronizer(identifier, FileSynchronizer, **kwargs)
 
+
 def mutex_synchronizer(identifier, **kwargs):
     return _synchronizer(identifier, ConditionSynchronizer, **kwargs)
 
+
 class null_synchronizer(object):
     def acquire_write_lock(self, wait=True):
         return True
         pass
     acquire = acquire_write_lock
     release = release_write_lock
-    
+
+
 class SynchronizerImpl(object):
-
     def __init__(self):
         self._state = util.ThreadLocal()
 
     
     def do_acquire_write_lock(self):
         raise NotImplementedError()
-    
+
+
 class FileSynchronizer(SynchronizerImpl):
     """a synchronizer which locks using flock()."""
 
                 # occasionally another thread beats us to it
                 pass                    
 
+
 class ConditionSynchronizer(SynchronizerImpl):
     """a synchronizer using a Condition."""
     
                 if self.current_sync_operation is not None:
                     self.condition.notifyAll()
             elif self.async < 0:
-                raise LockError("Synchronizer error - too many release_read_locks called")
+                raise LockError("Synchronizer error - too many "
+                                "release_read_locks called")
         finally:
             self.condition.release()
     
         self.condition.acquire()
         try:
             if self.current_sync_operation is not _threading.currentThread():
-                raise LockError("Synchronizer error - current thread doesnt have the write lock")
+                raise LockError("Synchronizer error - current thread doesnt "
+                                "have the write lock")
 
             # reset the current sync operation so 
             # another can get it
-__all__  = ["ThreadLocal", "Registry", "WeakValuedRegistry", "SyncDict", "encoded_path", "verify_directory"]
-
+"""Beaker utilities"""
 try:
     import thread as _thread
     import threading as _threading
             raise TypeError(msg)
 
 
+__all__  = ["ThreadLocal", "Registry", "WeakValuedRegistry", "SyncDict",
+            "encoded_path", "verify_directory"]
+
+
 def verify_directory(dir):
     """verifies and creates a directory.  tries to
     ignore collisions with other threads and processes."""
     
 class SyncDict(object):
     """
-    an efficient/threadsafe singleton map algorithm, a.k.a.
-    "get a value based on this key, and create if not found or not valid" paradigm:
+    An efficient/threadsafe singleton map algorithm, a.k.a.
+    "get a value based on this key, and create if not found or not
+    valid" paradigm:
     
         exists && isvalid ? get : create
 
-    works with weakref dictionaries and the LRUCache to handle items asynchronously 
-    disappearing from the dictionary.  
+    Works with weakref dictionaries and the LRUCache to handle items
+    asynchronously disappearing from the dictionary.  
 
-    use python 2.3.3 or greater !  a major bug was just fixed in Nov. 2003 that
-    was driving me nuts with garbage collection/weakrefs in this section.
-    """
-    
+    Use python 2.3.3 or greater !  a major bug was just fixed in Nov.
+    2003 that was driving me nuts with garbage collection/weakrefs in
+    this section.
+
+    """    
     def __init__(self):
         self.mutex = _thread.allocate_lock()
         self.dict = {}
     def clear(self):
         self.dict.clear()
 
-    
 
 class WeakValuedRegistry(SyncDict):
     def __init__(self):
         self.mutex = _threading.RLock()
         self.dict = weakref.WeakValueDictionary()
+
             
-def encoded_path(root, identifiers, extension = ".enc", depth = 3, digest_filenames=True):
-    """generate a unique file-accessible path from the given list of identifiers
-    starting at the given root directory."""
+def encoded_path(root, identifiers, extension = ".enc", depth = 3,
+                 digest_filenames=True):
+    """Generate a unique file-accessible path from the given list of
+    identifiers starting at the given root directory."""
     ident = string.join(identifiers, "_")
 
     if digest_filenames:
     
     return os.path.join(dir, ident + extension)
 
+
 def verify_options(opt, types, error):
     if not isinstance(opt, types):
         if not isinstance(types, tuple):
             raise Exception(error)
     return opt
 
+
 def verify_rules(params, ruleset):
     for key, types, message in ruleset:
         if key in params:
             params[key] = verify_options(params[key], types, message)
     return params
 
+
 def coerce_session_params(params):
     rules = [
-        ('data_dir', (str, types.NoneType), "data_dir must be a string referring to a directory."),
-        ('lock_dir', (str,), "lock_dir must be a string referring to a directory."),
+        ('data_dir', (str, types.NoneType), "data_dir must be a string "
+         "referring to a directory."),
+        ('lock_dir', (str,), "lock_dir must be a string referring to a "
+         "directory."),
         ('type', (str, types.NoneType), "Session type must be a string."),
-        ('cookie_expires', (bool, datetime, timedelta), "Cookie expires was not a boolean, datetime, or timedelta instance."),
-        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a string."),
+        ('cookie_expires', (bool, datetime, timedelta), "Cookie expires was "
+         "not a boolean, datetime, or timedelta instance."),
+        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a "
+         "string."),
         ('id', (str,), "Session id must be a string."),
         ('key', (str,), "Session key must be a string."),
         ('secret', (str, types.NoneType), "Session secret must be a string."),
-        ('validate_key', (str, types.NoneType), "Session encrypt_key must be a string."),
-        ('encrypt_key', (str, types.NoneType), "Session validate_key must be a string."),
+        ('validate_key', (str, types.NoneType), "Session encrypt_key must be "
+         "a string."),
+        ('encrypt_key', (str, types.NoneType), "Session validate_key must be "
+         "a string."),
         ('secure', (bool, types.NoneType), "Session secure must be a boolean."),
-        ('timeout', (int, types.NoneType), "Session timeout must be an integer."),
+        ('timeout', (int, types.NoneType), "Session timeout must be an "
+         "integer."),
     ]
     return verify_rules(params, rules)
 
+
 def coerce_cache_params(params):
     rules = [
-        ('data_dir', (str, types.NoneType), "data_dir must be a string referring to a directory."),
-        ('lock_dir', (str,), "lock_dir must be a string referring to a directory."),
+        ('data_dir', (str, types.NoneType), "data_dir must be a string "
+         "referring to a directory."),
+        ('lock_dir', (str,), "lock_dir must be a string referring to a "
+         "directory."),
         ('type', (str,), "Session type must be a string."),
     ]
     return verify_rules(params, rules)