PKS#68ž&Šd¹¹beaker/exceptions.pyc;ò €LäFc@s\defd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdS( sBeakerExceptioncBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/exceptions.pysBeakerExceptionssInvalidCacheBackendErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/exceptions.pysInvalidCacheBackendErrorssMissingCacheParametercBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/exceptions.pysMissingCacheParameterss LockErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/exceptions.pys LockError sN(s ExceptionsBeakerExceptionsInvalidCacheBackendErrorsMissingCacheParameters LockError(sInvalidCacheBackendErrors LockErrorsMissingCacheParametersBeakerException((s5build/bdist.darwin-8.0.1-x86/egg/beaker/exceptions.pys?sPKT#68·_L›&&beaker/cache.pyc;ò €LäFc@sGdkZdkiZdklZdklZdkiZy dkl Z e ddƒZ Wn e Z nXhdei <dei <dei 0: if wait: # wait self.condition.wait() else: # we dont want to wait, so forget it self.current_sync_operation = None self.condition.release() return False self.condition.release() if not wait: return True def do_release_write_lock(self): self.condition.acquire() if self.current_sync_operation != _threading.currentThread(): raise LockError("Synchronizer error - current thread doesnt have the write lock") # reset the current sync operation so # another can get it self.current_sync_operation = None # tell everyone to get ready self.condition.notifyAll() # everyone go !! self.condition.release() PK:})7€Œ¥beaker/__init__.py# PK:})7{í¼©žžbeaker/util.py__all__ = ["ThreadLocal", "Registry", "WeakValuedRegistry", "SyncDict", "encoded_path", "verify_directory"] try: import thread as _thread import threading as _threading except ImportError: import dummy_thread as _thread import dummy_threading as _threading from datetime import datetime, timedelta import os import sha import string import types import weakref try: Set = set except NameError: from sets import Set from beaker.converters import asbool def verify_directory(dir): """verifies and creates a directory. tries to ignore collisions with other threads and processes.""" tries = 0 while not os.access(dir, os.F_OK): try: tries += 1 os.makedirs(dir, 0750) except: if tries > 5: raise class ThreadLocal(object): """stores a value on a per-thread basis""" def __init__(self, value = None, default = None, creator = None): self.dict = {} self.default = default self.creator = creator if value: self.put(value) def __call__(self, *arg): if len(arg): self.put(arg[0]) else: return self.get() def __str__(self): return str(self.get()) def assign(self, value): self.dict[_thread.get_ident()] = value def put(self, value): self.assign(value) def exists(self): return self.dict.has_key(_thread.get_ident()) def get(self, *args, **params): if not self.dict.has_key(_thread.get_ident()): if self.default is not None: self.put(self.default) elif self.creator is not None: self.put(self.creator(*args, **params)) return self.dict[_thread.get_ident()] def remove(self): del self.dict[_thread.get_ident()] 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: exists && isvalid ? get : create 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. """ def __init__(self, mutex, dictionary): self.mutex = mutex self.dict = dictionary def clear(self): self.dict.clear() def get(self, key, createfunc, isvalidfunc = None): """regular get method. returns the object asynchronously, if present and also passes the optional isvalidfunc, else defers to the synchronous get method which will create it.""" try: if self.has_key(key): return self._get_obj(key, createfunc, isvalidfunc) else: return self.sync_get(key, createfunc, isvalidfunc) except KeyError: return self.sync_get(key, createfunc, isvalidfunc) def sync_get(self, key, createfunc, isvalidfunc = None): self.mutex.acquire() try: try: if self.has_key(key): return self._get_obj(key, createfunc, isvalidfunc, create = True) else: return self._create(key, createfunc) except KeyError: return self._create(key, createfunc) finally: self.mutex.release() def _get_obj(self, key, createfunc, isvalidfunc, create = False): obj = self[key] if isvalidfunc is not None and not isvalidfunc(obj): if create: return self._create(key, createfunc) else: return self.sync_get(key, createfunc, isvalidfunc) else: return obj def _create(self, key, createfunc): obj = createfunc() self[key] = obj return obj def has_key(self, key): return self.dict.has_key(key) def __contains__(self, key): return self.dict.__contains__(key) def __getitem__(self, key): return self.dict.__getitem__(key) def __setitem__(self, key, value): self.dict.__setitem__(key, value) def __delitem__(self, key): return self.dict.__delitem__(key) class Registry(SyncDict): """a registry object.""" def __init__(self): SyncDict.__init__(self, _threading.Lock(), {}) class WeakValuedRegistry(SyncDict): """a registry that stores objects only as long as someone has a reference to them.""" def __init__(self): # weakrefs apparently can trigger the __del__ method of other # unreferenced objects, when you create a new reference. this can occur # when you place new items into the WeakValueDictionary. if that __del__ # method happens to want to access this same registry, well, then you need # the RLock instead of a regular lock, since at the point of dictionary # insertion, we are already inside the lock. SyncDict.__init__(self, _threading.RLock(), weakref.WeakValueDictionary()) def encoded_path(root, identifiers, extension = ".enc", depth = 3, digest = 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: ident = sha.new(ident).hexdigest() tokens = [] for d in range(1, depth): tokens.append(ident[0:d]) dir = os.path.join(root, *tokens) verify_directory(dir) return os.path.join(dir, ident + extension) def verify_options(opt, types, error): if not isinstance(opt, types): if not isinstance(types, tuple): types = (types,) coerced = False for typ in types: try: if typ == bool: typ = asbool opt = typ(opt) coerced = True except: pass if coerced: break if not coerced: 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."), ('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."), ('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."), ('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."), ('type', (str,), "Session type must be a string."), ] return verify_rules(params, rules) PK:})7 ¸__beaker/converters.py# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php def asbool(obj): if isinstance(obj, (str, unicode)): obj = obj.strip().lower() if obj in ['true', 'yes', 'on', 'y', 't', '1']: return True elif obj in ['false', 'no', 'off', 'n', 'f', '0']: return False else: raise ValueError( "String is not true/false: %r" % obj) return bool(obj) def aslist(obj, sep=None, strip=True): if isinstance(obj, (str, unicode)): lst = obj.split(sep) if strip: lst = [v.strip() for v in lst] return lst elif isinstance(obj, (list, tuple)): return obj elif obj is None: return [] else: return [obj] PKS#68°÷ú¼¨¼¨beaker/container.pyc;ò PëGc @sÃdkZdkZdkZdkZdkZdkZdkZdkl Z dk i Z dk l Z lZlZlZddddddd d d d d dg Zd„Zd„Zd„ZeidƒZed„Zdefd„ƒYZdefd„ƒYZdefd„ƒYZd efd„ƒYZdefd„ƒYZdefd„ƒYZ d efd„ƒYZ!defd„ƒYZ"e!Z#e"Z$d efd„ƒYZ%d efd„ƒYZ&dS(N(sMissingCacheParameter(s _threadings_threads SynchronizersNameLocksContainerContexts ContainersMemoryContainers DBMContainersNamespaceManagersMemoryNamespaceManagersDBMNamespaceManagers FileContainersFileNamespaceManagersCreationAbortedErrorscontainer_registrysnamespace_registrycCst|dƒSdS(smgiven the string name of a Namespace 'type', return the NamespaceManager subclass corresponding to that type.sNamespaceManagerN(s _cls_registrysname(sname((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysnamespace_registryscCst|dƒSdS(sfgiven the string name of a Container 'type', return the Container subclass corresponding to that type.s ContainerN(s _cls_registrysname(sname((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyscontainer_registryscCs˜|idƒp|ddgjoD|idƒo|d}nd|}tt|ƒi|ƒ}ntit }t i |ƒ|}t||ƒSdS(Nsext:s memcachedsdatabaseis beaker.ext.(snames startswithsmodnamesgetattrs __import__sextsmodssyssmoduless__name__sstrings capitalizesclsnamescname(snamesclsnamesmodnamescnamesmod((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys _cls_registrys#  sbeaker.containercCsntitiƒoW|tj o&d|ii|i |i |f}nd|i |f}ti |ƒndS(Ns[%s:%s:%s] %s s[%s] %s ( sloggers isEnabledForsloggingsDEBUGs containersNones __class__s__name__snsms namespaceskeysmessagesdebug(smessagesnsms container((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdebug+s  &cBsàtZdZd„Zd„Zd„Zed„Zd„Zd„Z d„Z d„Z d „Z d „Z d „Zd „Zd „Zd„Zd„Zd„Zd„Zed„Zd„Zed„Zed„Zd„ZRS(sƒhandles dictionary operations and locking for a namespace of values. 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. 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. cKs%||_d|_tiƒ|_dS(Ni(s namespacesselfsopenerss _threadingsLocksmutex(sselfs namespaceskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys__init__Is  cCs tƒ‚dS(N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_read_lockNscCs tƒ‚dS(N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_read_lockOscCs tƒ‚dS(N(sNotImplementedError(sselfswait((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_write_lockPscCs tƒ‚dS(N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_write_lockQscCs tƒ‚dS(N(sNotImplementedError(sselfsflags((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_openSscCs tƒ‚dS(N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_closeTscCs tƒ‚dS(s1removes this namespace from wherever it is storedN(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys do_removeVscCst||ƒdS(N(sdebugsmsgsself(sselfsmsg((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdebugZscCs|i|ƒSdS(N(sselfs __contains__skey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyshas_key]scCs tƒ‚dS(N(sNotImplementedError(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __getitem__`scCs tƒ‚dS(N(sNotImplementedError(sselfskeysvalue((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __setitem__cscCs tƒ‚dS(N(sNotImplementedError(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __contains__fscCs tƒ‚dS(N(sNotImplementedError(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __delitem__iscCs tƒ‚dS(N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyskeyslscCs<|iƒy|iddtƒWn|iƒ‚nXdS(sØacquires a read lock for this namespace, and insures that the datasource has been opened for reading if it is not already opened. acquire/release supports reentrant/nested operation.srs checkcountN(sselfsdo_acquire_read_locksopensTruesdo_release_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysacquire_read_lockos  cCs&z|idtƒWd|iƒXdS(såreleases the read lock for this namespace, and possibly closes the datasource, if it was opened as a product of the read lock's acquire/release block. acquire/release supports reentrant/nested operation.s checkcountN(sselfsclosesTruesdo_release_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysrelease_read_lock}s cCsW|i|ƒ}y-|p|o|iddtƒn|SWn|iƒ‚nXdS(sÑacquires a write lock for this namespace, and insures that the datasource has been opened for writing if it is not already opened. acquire/release supports reentrant/nested operation.scs checkcountN(sselfsdo_acquire_write_lockswaitsrsopensTruesdo_release_write_lock(sselfswaitsr((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysacquire_write_lock‰s cCs&z|idtƒWd|iƒXdS(sçreleases the write lock for this namespace, and possibly closes the datasource, if it was opened as a product of the write lock's acquire/release block. acquire/release supports reentrant/nested operation.s checkcountN(sselfsclosesTruesdo_release_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysrelease_write_lock˜s cCsw|iiƒzU|o4|idjo|i|ƒn|id7_n|i|ƒd|_Wd|iiƒXdS(säopens the datasource for this namespace. the checkcount flag indicates an "opened" counter should be checked for zero before performing the open operation, which is incremented by one regardless.iiN(sselfsmutexsacquires checkcountsopenerssdo_opensflagssrelease(sselfsflagss checkcount((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysopen¤s   cCs…|iiƒzc|o1|id8_|idjo|iƒqon(|idjo|iƒnd|_Wd|iiƒXdS(såcloses the datasource for this namespace. the checkcount flag indicates an "opened" counter should be checked for zero before performing the close operation, which is otherwise decremented by one.iiN(sselfsmutexsacquires checkcountsopenerssdo_closesrelease(sselfs checkcount((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysclose¶s  cCs:|iƒz|idtƒ|iƒWd|iƒXdS(Ns checkcount(sselfsdo_acquire_write_locksclosesFalses do_removesdo_release_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysremoveÊs  (s__name__s __module__s__doc__s__init__sdo_acquire_read_locksdo_release_read_locksTruesdo_acquire_write_locksdo_release_write_locksdo_opensdo_closes do_removesdebugshas_keys __getitem__s __setitem__s __contains__s __delitem__skeyssacquire_read_locksrelease_read_locksacquire_write_locksrelease_write_locksFalsesopensclosesremove(((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysNamespaceManager5s.                    cBs)tZdZd„Zd„Zd„ZRS(sˆinitial context supplied to Containers. Keeps track of namespacemangers keyed off of namespace names and container types. cCs h|_dS(N(sselfsregistry(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys__init__ÚscKsY|id|}y|i|SWn2tj o&|ii||i||ƒSnXdS(s return a NamespaceManager corresponding to the given namespace name and container class. if no NamespaceManager exists, one will be created. namespace string name of the namespace container_class a Container subclass \**kwargs additional keyword arguments will be used as constructor arguments for the Namespace, in the case that one does not exist already. s|N( scontainer_classs__name__s namespaceskeysselfsregistrysKeyErrors setdefaultscreate_namespaceskwargs(sselfs namespacescontainer_classskwargsskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysget_namespace_managerÝs cCs|iiƒdS(N(sselfsregistrysclear(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysclearòs(s__name__s __module__s__doc__s__init__sget_namespace_managersclear(((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysContainerContextÔs   cBsøtZdZeeed„Zd„Zd„Zed„Zd„Z d„Z d„Z e e ƒZ d„Z d „Zd „Zd „Zd „Zed „Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„ZRS(s2represents a value, its stored time, and a value creation function corresponding to a particular key in a particular namespace. handles storage and retrieval of its value via a single NamespaceManager, as well as handling expiration times and an optional creation function that can create or recreate its value when needed. the Container performs locking operations on the NamespaceManager, including a pretty intricate one for get_value with a creation function, so its best not to pass a NamespaceManager that is in a locked or opened state. Managing a set of Containers for a given set of keys allows each key to be stored with a distinct namespace implementation (i.e. memory for one, DBM for another), expiration attribute and value-creation function. cKsY||_||_||_||_d|_|i||i ||_ |i |dS(srcreate a container that stores one cached object. createfunc - a function that will create the value. this function is called when value is None or expired. the createfunc call is also synchronized against any other threads or processes calling this cache. expiretime - time in seconds that the item expires. iÿÿÿÿN( skeysselfs createfuncs expiretimes starttimes storedtimescontextsget_namespace_managers namespaces __class__skwargssnamespacemanagersdo_init(sselfskeyscontexts namespaces createfuncs expiretimes starttimeskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys__init__s     cCs|iiƒdS(N(sselfsnamespacemanagersacquire_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysacquire_read_lockscCs|iiƒdS(N(sselfsnamespacemanagersrelease_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysrelease_read_lockscCs|ii|ƒSdS(N(sselfsnamespacemanagersacquire_write_lockswait(sselfswait((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysacquire_write_lockscCs|iiƒdS(N(sselfsnamespacemanagersrelease_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysrelease_write_lock!scCst||id|ƒdS(Ns container(sdebugsmessagesselfsnamespacemanager(sselfsmessage((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdebug$scKs tƒ‚dS(sRcreate a new instance of NamespaceManager corresponding to this Container's class.N(sNotImplementedError(sclsscontexts namespaceskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyscreate_namespace'scKsdS(sYsubclasses can perform general initialization. optional template method.N((sselfskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_init,scCs|i|iSdS(sªretrieves the native stored value of this container, regardless of if its expired, or raise KeyError if no value is defined. optionally a template method.N(sselfsnamespacemanagerskey(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys do_get_value2scCs||i|iscCs3|iƒz|ii|iƒSWd|iƒXdS(sreturns true if the container has a value stored, regardless of it being expired or not. optionally a template method.N(sselfsacquire_read_locksnamespacemanagershas_keyskeysrelease_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys has_valueHs  cCs tƒ‚dS(s„required template method that locks this container's namespace and key to allow a single execution of the creation function.N(sNotImplementedError(sselfswait((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyslock_createfuncUscCs tƒ‚dS(sxrequired template method that unlocks this container's namespace and key when the creation function is complete.N(sNotImplementedError(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysunlock_createfunc[scCs|iƒp |itj SdS(s|returns true if this container either has a non-expired value, or is capable of creating one via a creation functionN(sselfshas_current_values createfuncsNone(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyscan_have_valueascCs|iƒo |iƒ SdS(s6returns true if this container has a non-expired valueN(sselfs has_values is_expired(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyshas_current_valuefscCs |iSdS(N(sselfs storedtime(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys stored_timejscCs |iSdS(N(sselfsnamespacemanager(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysget_namespace_managermscCs|iiiiƒSdS(N(sselfsnamespacemanagerscontexts_container_namespacessvalues(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysget_all_namespacespscCsQ|itj o|i|ijp*|itj otiƒ|i|ijSdS(sgreturns true if this container's value is expired, based on the last time get_value was called.N(sselfs starttimesNones storedtimes expiretimestime(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys is_expiredsscCsÀ|iƒzg|iƒ}|o/|iƒ\|_}|iƒ o|SqOn|iƒ ot|i ƒ‚nWd|i ƒXt }|o@|i dt ƒ o|idƒ|SqÌ|idƒt}n| o(|idƒ|i ƒ|idƒnz¥|iƒz@|iƒo/|iƒ\|_}|iƒ o|SqHnWd|i ƒX|idƒy|iƒ}Wntj o }‚nX|i|ƒ|SWd|iƒ|idƒXdS( sÏget_value performs a get with expiration checks on its namespacemanager. if a creation function is specified, a new value will be created if the existing value is nonexistent or has expired.Nswaits6get_value returning old value while new one is createdslock_creatfunc (didnt wait)slock_createfunc (waiting)slock_createfunc (waited)sget_value creating new valuesunlock_createfunc(sselfsacquire_read_locks has_values do_get_values storedtimesvalues is_expiredscan_have_valuesKeyErrorskeysrelease_read_locksFalseshas_createlockslock_createfuncsdebugsTrues createfuncsvsCreationAbortedErrorses set_valuesunlock_createfunc(sselfshas_createlocks has_valuesvaluesvse((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys get_value‚sT               cCsY|iƒz=tiƒ|_|id|iƒ|i|i|gƒWd|iƒXdS(Nsset_value stored time %d(sselfsacquire_write_lockstimes storedtimesdebugs do_set_valuesvaluesrelease_write_lock(sselfsvalue((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys set_value½s cCs@|iƒz$|idƒ|iƒd|_Wd|iƒXdS(Ns clear_valueiÿÿÿÿ(sselfsacquire_write_locksdebugsdo_clear_values storedtimesrelease_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys clear_valueÆs    (s__name__s __module__s__doc__sNones__init__sacquire_read_locksrelease_read_locksTruesacquire_write_locksrelease_write_locksdebugscreate_namespaces classmethodsdo_inits do_get_values do_set_valuesdo_clear_values has_valueslock_createfuncsunlock_createfuncscan_have_valueshas_current_values stored_timesget_namespace_managersget_all_namespacess is_expireds get_values set_values clear_value(((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys Containerõs2                    ; cBstZdZRS(sDan exception that allows a creation function to abort what its doing(s__name__s __module__s__doc__(((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysCreationAbortedErrorÏs cBs¡tZeieiƒhƒZd„Zd„Zd„Z e d„Z d„Z d„Z d„Zd„Zd „Zd „Zd „Zd „Zd „Zd„ZRS(NcKsTti|||tdd|idtƒ|_ti i |id„ƒ|_ dS(Ns identifiers memorycontainer/namespacelock/%ss use_filescCshS(N((((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysÜs( sNamespaceManagers__init__sselfs namespaceskwargss SynchronizersFalseslocksMemoryNamespaceManagers namespacessgets dictionary(sselfs namespaceskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys__init__×scCs|iiƒdS(N(sselfslocksacquire_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_read_lockÞscCs|iiƒdS(N(sselfslocksrelease_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_read_lockßscCs|ii|ƒSdS(N(sselfslocksacquire_write_lockswait(sselfswait((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_write_lockàscCs|iiƒdS(N(sselfslocksrelease_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_write_lockáscOsdS(N((sselfsargsskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysopenåscOsdS(N((sselfsargsskwargs((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyscloseæscCs|i|SdS(N(sselfs dictionaryskey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __getitem__èscCs|ii|ƒSdS(N(sselfs dictionarys __contains__skey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __contains__êscCs|ii|ƒSdS(N(sselfs dictionarys __contains__skey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pyshas_keyíscCs||i||i|iƒ o&|ii|idƒ}|iƒndS(Nsc(sselfs file_existssfiles dbmmodulesopensgsclose(sselfsg((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys _checkfile?scCs›g}ti|itiƒo|i|iƒnx]ddddfD]I}ti|iti|tiƒo|i|iti|ƒqFqFW|SdS(Nspagsdirsdbsdat( slistsossaccesssselfsfilesF_OKsappendsextsextsep(sselfslistsext((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys get_filenamesDs$#cCs|iiƒdS(N(sselfslocksacquire_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_read_lockOscCs|iiƒdS(N(sselfslocksrelease_read_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_read_lockRscCs|ii|ƒSdS(N(sselfslocksacquire_write_lockswait(sselfswait((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_acquire_write_lockUscCs|iiƒdS(N(sselfslocksrelease_write_lock(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_release_write_lockXscCsf|id|iƒy|ii|i|ƒ|_Wn,|iƒ|ii|i|ƒ|_nXdS(Nsopening dbm file %s(sselfsdebugsfiles dbmmodulesopensflagssdbms _checkfile(sselfsflags((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_open[s  cCs9|itj o%|id|iƒ|iiƒndS(Nsclosing dbm file %s(sselfsdbmsNonesdebugsfilesclose(sself((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pysdo_closeiscCs(x!|iƒD]}ti|ƒq WdS(N(sselfs get_filenamessfsossremove(sselfsf((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys do_removens cCsti|i|ƒSdS(N(scPicklesloadssselfsdbmskey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __getitem__rscCs|ii|ƒSdS(N(sselfsdbmshas_keyskey(sselfskey((s4build/bdist.darwin-8.0.1-x86/egg/beaker/container.pys __contains__uscCsti|ƒ|i| 0: self.do_close() self.openers = 0 finally: self.mutex.release() def remove(self): self.do_acquire_write_lock() try: self.close(checkcount = False) self.do_remove() finally: self.do_release_write_lock() class ContainerContext(object): """initial context supplied to Containers. Keeps track of namespacemangers keyed off of namespace names and container types. """ def __init__(self): self.registry = {} def get_namespace_manager(self, namespace, container_class, **kwargs): """return a NamespaceManager corresponding to the given namespace name and container class. if no NamespaceManager exists, one will be created. namespace string name of the namespace container_class a Container subclass \**kwargs additional keyword arguments will be used as constructor arguments for the Namespace, in the case that one does not exist already. """ key = container_class.__name__ + "|" + namespace try: return self.registry[key] except KeyError: return self.registry.setdefault(key, container_class.create_namespace(namespace, **kwargs)) def clear(self): self.registry.clear() class Container(object): """represents a value, its stored time, and a value creation function corresponding to a particular key in a particular namespace. handles storage and retrieval of its value via a single NamespaceManager, as well as handling expiration times and an optional creation function that can create or recreate its value when needed. the Container performs locking operations on the NamespaceManager, including a pretty intricate one for get_value with a creation function, so its best not to pass a NamespaceManager that is in a locked or opened state. Managing a set of Containers for a given set of keys allows each key to be stored with a distinct namespace implementation (i.e. memory for one, DBM for another), expiration attribute and value-creation function. """ def __init__(self, key, context, namespace, createfunc=None, expiretime=None, starttime=None, **kwargs): """create a container that stores one cached object. createfunc - a function that will create the value. this function is called when value is None or expired. the createfunc call is also synchronized against any other threads or processes calling this cache. expiretime - time in seconds that the item expires. """ self.key = key self.createfunc = createfunc self.expiretime = expiretime self.starttime = starttime self.storedtime = -1 # TODO: consume **kwargs for Namespace and do_init separately, raise errors for remaining kwargs self.namespacemanager = context.get_namespace_manager(namespace, self.__class__, **kwargs) self.do_init(**kwargs) def acquire_read_lock(self): self.namespacemanager.acquire_read_lock() def release_read_lock(self): self.namespacemanager.release_read_lock() def acquire_write_lock(self, wait = True): return self.namespacemanager.acquire_write_lock(wait) def release_write_lock(self): self.namespacemanager.release_write_lock() def debug(self, message): debug(message, self.namespacemanager, container=self) def create_namespace(cls, context, namespace, **kwargs): """create a new instance of NamespaceManager corresponding to this Container's class.""" raise NotImplementedError() create_namespace = classmethod(create_namespace) def do_init(self, **kwargs): """subclasses can perform general initialization. optional template method.""" pass def do_get_value(self): """retrieves the native stored value of this container, regardless of if its expired, or raise KeyError if no value is defined. optionally a template method.""" return self.namespacemanager[self.key] def do_set_value(self, value): """sets the raw value in this container. optionally a template method.""" self.namespacemanager[self.key] = value def do_clear_value(self): """clears the value of this container. subsequent do_get_value calls should raise KeyError. optionally a template method.""" if self.namespacemanager.has_key(self.key): del self.namespacemanager[self.key] def has_value(self): """returns true if the container has a value stored, regardless of it being expired or not. optionally a template method.""" self.acquire_read_lock() try: return self.namespacemanager.has_key(self.key) finally: self.release_read_lock() def lock_createfunc(self, wait = True): """required template method that locks this container's namespace and key to allow a single execution of the creation function.""" raise NotImplementedError() def unlock_createfunc(self): """required template method that unlocks this container's namespace and key when the creation function is complete.""" raise NotImplementedError() def can_have_value(self): """returns true if this container either has a non-expired value, or is capable of creating one via a creation function""" return self.has_current_value() or self.createfunc is not None def has_current_value(self): """returns true if this container has a non-expired value""" return self.has_value() and not self.is_expired() def stored_time(self): return self.storedtime def get_namespace_manager(self): return self.namespacemanager def get_all_namespaces(self): return self.namespacemanager.context._container_namespaces.values() def is_expired(self): """returns true if this container's value is expired, based on the last time get_value was called.""" return ( ( self.starttime is not None and self.storedtime < self.starttime ) or ( self.expiretime is not None and time.time() >= self.expiretime + self.storedtime ) ) def get_value(self): """get_value performs a get with expiration checks on its namespacemanager. if a creation function is specified, a new value will be created if the existing value is nonexistent or has expired.""" self.acquire_read_lock() try: has_value = self.has_value() if has_value: [self.storedtime, value] = self.do_get_value() if not self.is_expired(): return value if not self.can_have_value(): raise KeyError(self.key) finally: self.release_read_lock() has_createlock = False if has_value: if not self.lock_createfunc(wait = False): self.debug("get_value returning old value while new one is created") return value else: self.debug("lock_creatfunc (didnt wait)") has_createlock = True if not has_createlock: self.debug("lock_createfunc (waiting)") self.lock_createfunc() self.debug("lock_createfunc (waited)") try: # see if someone created the value already self.acquire_read_lock() try: if self.has_value(): [self.storedtime, value] = self.do_get_value() if not self.is_expired(): return value finally: self.release_read_lock() self.debug("get_value creating new value") try: v = self.createfunc() except CreationAbortedError, e: raise self.set_value(v) return v finally: self.unlock_createfunc() self.debug("unlock_createfunc") def set_value(self, value): self.acquire_write_lock() try: self.storedtime = time.time() self.debug("set_value stored time %d" % self.storedtime) self.do_set_value([self.storedtime, value]) finally: self.release_write_lock() def clear_value(self): self.acquire_write_lock() try: self.debug("clear_value") self.do_clear_value() self.storedtime = -1 finally: self.release_write_lock() class CreationAbortedError(Exception): """an exception that allows a creation function to abort what its doing""" pass class MemoryNamespaceManager(NamespaceManager): namespaces = util.SyncDict(_threading.Lock(), {}) def __init__(self, namespace, **kwargs): NamespaceManager.__init__(self, namespace, **kwargs) self.lock = Synchronizer(identifier = "memorycontainer/namespacelock/%s" % self.namespace, use_files = False) self.dictionary = MemoryNamespaceManager.namespaces.get(self.namespace, lambda: {}) def do_acquire_read_lock(self): self.lock.acquire_read_lock() def do_release_read_lock(self): self.lock.release_read_lock() def do_acquire_write_lock(self, wait = True): return self.lock.acquire_write_lock(wait) def do_release_write_lock(self): self.lock.release_write_lock() # the open and close methods are totally overridden to eliminate # the unnecessary "open count" computation involved def open(self, *args, **kwargs):pass def close(self, *args, **kwargs):pass def __getitem__(self, key): return self.dictionary[key] def __contains__(self, key): return self.dictionary.__contains__(key) def has_key(self, key): return self.dictionary.__contains__(key) def __setitem__(self, key, value):self.dictionary[key] = value def __delitem__(self, key): del self.dictionary[key] def do_remove(self): self.dictionary.clear() def keys(self): return self.dictionary.keys() class MemoryContainer(Container): def do_init(self, **kwargs): self.funclock = None def create_namespace(cls, namespace, **kwargs): return MemoryNamespaceManager(namespace, **kwargs) create_namespace = classmethod(create_namespace) def lock_createfunc(self, wait = True): if self.funclock is None: self.funclock = NameLock(identifier = "memorycontainer/funclock/%s/%s" % (self.namespacemanager.namespace, self.key), reentrant = True) return self.funclock.acquire(wait) def unlock_createfunc(self): self.funclock.release() class DBMNamespaceManager(NamespaceManager): def __init__(self, namespace, dbmmodule = None, data_dir = None, dbm_dir = None, lock_dir = None, digest_filenames = True, **kwargs): NamespaceManager.__init__(self, namespace, **kwargs) if dbm_dir is not None: self.dbm_dir = dbm_dir elif data_dir is None: raise MissingCacheParameter("data_dir or dbm_dir is required") else: self.dbm_dir = data_dir + "/container_dbm" if lock_dir is not None: self.lock_dir = lock_dir elif data_dir is None: raise MissingCacheParameter("data_dir or lock_dir is required") else: self.lock_dir = data_dir + "/container_dbm_lock" if dbmmodule is None: self.dbmmodule = anydbm else: self.dbmmodule = dbmmodule util.verify_directory(self.dbm_dir) util.verify_directory(self.lock_dir) self.dbm = None self.lock = Synchronizer(identifier=self.namespace, use_files=True, lock_dir=self.lock_dir, digest_filenames=digest_filenames) self.file = util.encoded_path(root= self.dbm_dir, identifiers=[self.namespace], digest=digest_filenames, extension='.dbm') self.debug("data file %s" % self.file) self._checkfile() def file_exists(self, file): if os.access(file, os.F_OK): return True else: for ext in ('db', 'dat', 'pag', 'dir'): if os.access(file + os.extsep + ext, os.F_OK): return True return False def _checkfile(self): if not self.file_exists(self.file): g = self.dbmmodule.open(self.file, 'c') g.close() def get_filenames(self): list = [] if os.access(self.file, os.F_OK): list.append(self.file) for ext in ('pag', 'dir', 'db', 'dat'): if os.access(self.file + os.extsep + ext, os.F_OK): list.append(self.file + os.extsep + ext) return list def do_acquire_read_lock(self): self.lock.acquire_read_lock() def do_release_read_lock(self): self.lock.release_read_lock() def do_acquire_write_lock(self, wait = True): return self.lock.acquire_write_lock(wait) def do_release_write_lock(self): self.lock.release_write_lock() def do_open(self, flags): # caution: apparently gdbm handles arent threadsafe, they # are using flock(), and i would rather not have knowledge # of the "unlock" 'u' option just for that one dbm module. # therefore, neither is an individual instance of # this namespacemanager (of course, multiple nsm's # can exist for each thread). self.debug("opening dbm file %s" % self.file) try: self.dbm = self.dbmmodule.open(self.file, flags) except: self._checkfile() self.dbm = self.dbmmodule.open(self.file, flags) def do_close(self): if self.dbm is not None: self.debug("closing dbm file %s" % self.file) self.dbm.close() def do_remove(self): for f in self.get_filenames(): os.remove(f) def __getitem__(self, key): return cPickle.loads(self.dbm[key]) def __contains__(self, key): return self.dbm.has_key(key) def __setitem__(self, key, value): self.dbm[key] = cPickle.dumps(value) def __delitem__(self, key): del self.dbm[key] def keys(self): return self.dbm.keys() class DBMContainer(Container): def do_init(self, **kwargs): self.funclock = None def create_namespace(cls, namespace, **kwargs): return DBMNamespaceManager(namespace, **kwargs) create_namespace = classmethod(create_namespace) def lock_createfunc(self, wait = True): if self.funclock is None: self.funclock = Synchronizer(identifier = "dbmcontainer/funclock/%s" % self.namespacemanager.namespace, use_files = True, lock_dir = self.namespacemanager.lock_dir) return self.funclock.acquire_write_lock(wait) def unlock_createfunc(self): self.funclock.release_write_lock() DbmNamespaceManager = DBMNamespaceManager DbmContainer = DBMContainer class FileNamespaceManager(NamespaceManager): def __init__(self, namespace, data_dir = None, file_dir = None, lock_dir = None, digest_filenames = True, **kwargs): NamespaceManager.__init__(self, namespace, **kwargs) if file_dir is not None: self.file_dir = file_dir elif data_dir is None: raise MissingCacheParameter("data_dir or file_dir is required") else: self.file_dir = data_dir + "/container_file" if lock_dir is not None: self.lock_dir = lock_dir elif data_dir is None: raise MissingCacheParameter("data_dir or lock_dir is required") else: self.lock_dir = data_dir + "/container_file_lock" util.verify_directory(self.file_dir) util.verify_directory(self.lock_dir) self.lock = Synchronizer(identifier=self.namespace, use_files=True, lock_dir=self.lock_dir, digest_filenames=digest_filenames) self.file = util.encoded_path(root=self.file_dir, identifiers=[self.namespace], digest=digest_filenames, extension='.cache') self.hash = {} self.debug("data file %s" % self.file) def file_exists(self, file): if os.access(file, os.F_OK): return True else: return False def do_acquire_read_lock(self): self.lock.acquire_read_lock() def do_release_read_lock(self): self.lock.release_read_lock() def do_acquire_write_lock(self, wait = True): return self.lock.acquire_write_lock(wait) def do_release_write_lock(self): self.lock.release_write_lock() def do_open(self, flags): if self.file_exists(self.file): fh = open(self.file, 'rb') try: self.hash = cPickle.load(fh) except (IOError, OSError, EOFError, cPickle.PickleError): pass fh.close() self.flags = flags def do_close(self): if self.flags is not None and (self.flags == 'c' or self.flags == 'w'): fh = open(self.file, 'wb') cPickle.dump(self.hash, fh) fh.close() self.flags = None def do_remove(self): os.remove(self.file) self.hash = {} def __getitem__(self, key): return self.hash[key] def __contains__(self, key): return self.hash.has_key(key) def __setitem__(self, key, value): self.hash[key] = value def __delitem__(self, key): del self.hash[key] def keys(self): return self.hash.keys() class FileContainer(Container): def do_init(self, **kwargs): self.funclock = None def create_namespace(cls, namespace, **kwargs): return FileNamespaceManager(namespace, **kwargs) create_namespace = classmethod(create_namespace) def lock_createfunc(self, wait = True): if self.funclock is None: self.funclock = Synchronizer(identifier = "filecontainer/funclock/%s" % self.namespacemanager.namespace, use_files = True, lock_dir = self.namespacemanager.lock_dir) return self.funclock.acquire_write_lock(wait) def unlock_createfunc(self): self.funclock.release_write_lock() PK‡47Ô÷Óáððbeaker/cookie.py""" Cookie handling portions of this code are copied from mod_python and licensed under the Apache license as follows: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Originally developed by Gregory Trubetskoy. """ import time import re import hmac import marshal import base64 class CookieError(Exception): pass class metaCookie(type): def __new__(cls, clsname, bases, clsdict): _valid_attr = ( "version", "path", "domain", "secure", "comment", "expires", "max_age", # RFC 2965 "commentURL", "discard", "port", # Microsoft Extension "httponly" ) # _valid_attr + property values # (note __slots__ is a new Python feature, it # prevents any other attribute from being set) __slots__ = _valid_attr + ("name", "value", "_value", "_expires", "__data__") clsdict["_valid_attr"] = _valid_attr clsdict["__slots__"] = __slots__ def set_expires(self, value): if type(value) == type(""): # if it's a string, it should be # valid format as per Netscape spec try: t = time.strptime(value, "%a, %d-%b-%Y %H:%M:%S GMT") except ValueError: raise ValueError, "Invalid expires time: %s" % value t = time.mktime(t) else: # otherwise assume it's a number # representing time as from time.time() t = value value = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", time.gmtime(t)) self._expires = "%s" % value def get_expires(self): return self._expires clsdict["expires"] = property(fget=get_expires, fset=set_expires) return type.__new__(cls, clsname, bases, clsdict) class Cookie(object): """ This class implements the basic Cookie functionality. Note that unlike the Python Standard Library Cookie class, this class represents a single cookie (not a list of Morsels). """ __metaclass__ = metaCookie DOWNGRADE = 0 IGNORE = 1 EXCEPTION = 3 def parse(Class, str, **kw): """ Parse a Cookie or Set-Cookie header value, and return a dict of Cookies. Note: the string should NOT include the header name, only the value. """ dict = _parse_cookie(str, Class, **kw) return dict parse = classmethod(parse) def __init__(self, name, value, **kw): """ This constructor takes at least a name and value as the arguments, as well as optionally any of allowed cookie attributes as defined in the existing cookie standards. """ self.name, self.value = name, value for k in kw: setattr(self, k.lower(), kw[k]) # subclasses can use this for internal stuff self.__data__ = {} def __str__(self): """ Provides the string representation of the Cookie suitable for sending to the browser. Note that the actual header name will not be part of the string. This method makes no attempt to automatically double-quote strings that contain special characters, even though the RFC's dictate this. This is because doing so seems to confuse most browsers out there. """ result = ["%s=%s" % (self.name, self.value)] for name in self._valid_attr: if hasattr(self, name): if name in ("secure", "discard", "httponly"): result.append(name) else: result.append("%s=%s" % (name, getattr(self, name))) return "; ".join(result) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, str(self)) class SignedCookie(Cookie): """ This is a variation of Cookie that provides automatic cryptographic signing of cookies and verification. It uses the HMAC support in the Python standard library. This ensures that the cookie has not been tamprered with on the client side. Note that this class does not encrypt cookie data, thus it is still plainly visible as part of the cookie. """ def parse(Class, s, secret, mismatch=Cookie.DOWNGRADE, **kw): dict = _parse_cookie(s, Class, **kw) del_list = [] for k in dict: c = dict[k] try: c.unsign(secret) except CookieError: if mismatch == Cookie.EXCEPTION: raise elif mismatch == Cookie.IGNORE: del_list.append(k) else: # downgrade to Cookie dict[k] = Cookie.parse(Cookie.__str__(c))[k] for k in del_list: del dict[k] return dict parse = classmethod(parse) def __init__(self, name, value, secret=None, **kw): Cookie.__init__(self, name, value, **kw) self.__data__["secret"] = secret def hexdigest(self, str): if not self.__data__["secret"]: raise CookieError, "Cannot sign without a secret" _hmac = hmac.new(self.__data__["secret"], self.name) _hmac.update(str) return _hmac.hexdigest() def __str__(self): result = ["%s=%s%s" % (self.name, self.hexdigest(self.value), self.value)] for name in self._valid_attr: if hasattr(self, name): if name in ("secure", "discard", "httponly"): result.append(name) else: result.append("%s=%s" % (name, getattr(self, name))) return "; ".join(result) def unsign(self, secret): sig, val = self.value[:32], self.value[32:] mac = hmac.new(secret, self.name) mac.update(val) if mac.hexdigest() == sig: self.value = val self.__data__["secret"] = secret else: raise CookieError, "Incorrectly Signed Cookie: %s=%s" % (self.name, self.value) # This is a simplified and in some places corrected # (at least I think it is) pattern from standard lib Cookie.py _cookiePattern = re.compile( r"(?x)" # Verbose pattern r"[,\ ]*" # space/comma (RFC2616 4.2) before attr-val is eaten r"(?P" # Start of group 'key' r"[^;\ =]+" # anything but ';', ' ' or '=' r")" # End of group 'key' r"\ *(=\ *)?" # a space, then may be "=", more space r"(?P" # Start of group 'val' r'"(?:[^\\"]|\\.)*"' # a doublequoted string r"|" # or r"[^;]*" # any word or empty string r")" # End of group 'val' r"\s*;?" # probably ending in a semi-colon ) def _parse_cookie(str, Class, names=None): # XXX problem is we should allow duplicate # strings result = {} matchIter = _cookiePattern.finditer(str) for match in matchIter: key, val = match.group("key"), match.group("val") # We just ditch the cookies names which start with a dollar sign since # those are in fact RFC2965 cookies attributes. See bug [#MODPYTHON-3]. if key[0]!='$' and names is None or key in names: result[key] = Class(key, val) return result PKR#68ÒÀÞdGdGbeaker/synchronization.pyc;ò €LäFc@sZddddgZdkZdkZdkZydkZdkZWn%ej odk Zdk ZnXyei ƒe Z Wn6ydkZeZ Wq¸ej o e Z q¸XnXdklZdklZdefd„ƒYZdefd„ƒYZd efd „ƒYZd efd „ƒYZd efd„ƒYZdefd„ƒYZdS(s SynchronizersNameLocks _threadings_threadN(sutil(s LockErrorcBsZtZdZeiƒZdfd„ƒYZeed„Z e d„Z d„Z d„Z RS(sß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. s NLContainercBs tZdZd„Zd„ZRS(scant put Lock as a weakrefcCs-|otiƒ|_ntiƒ|_dS(N(s reentrants _threadingsRLocksselfslocksLock(sselfs reentrant((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__(scCs |iSdS(N(sselfslock(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__call__-s(s__name__s __module__s__doc__s__init__s__call__(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys NLContainer&s  cCs|i||ƒ|_dS(N(sselfs _get_locks identifiers reentrantslock(sselfs identifiers reentrant((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__0scCs|iƒi|ƒSdS(N(sselfslocksacquireswait(sselfswait((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysacquire3scCs|iƒiƒdS(N(sselfslocksrelease(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease6scs;|tjotiˆƒSntii|‡d†ƒSdS(Ncs tiˆƒS(N(sNameLocks NLContainers reentrant((s reentrant(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys>s(s identifiersNonesNameLocks NLContainers reentrantslockssget(sselfs identifiers reentrant((s reentrants:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys _get_lock9s (s__name__s __module__s__doc__sutilsWeakValuedRegistryslockss NLContainersNonesFalses__init__sTruesacquiresreleases _get_lock(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysNameLocks     cBsYtZdZeiƒZeeeed„Z d„Z ed„Z ed„Z d„Z RS(sZa read-many/single-writer synchronizer which globally synchronizes on a given string name.csƒt o t}n|o8tiidˆ‡‡‡d†ƒ‰‡d†|_ n/tiidˆ‡d†ƒ‰‡d†|_ dS(Nsfile_%scstid‡‡‡d†ƒS(NscreatorcstˆˆˆƒS(N(sFileSynchronizers identifierslock_dirsdigest_filenames((sdigest_filenamess identifierslock_dir(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysMs(sutils ThreadLocal((sdigest_filenamesslock_dirs identifier(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysMscs ˆiƒS(N(ssyncssget((ssyncs(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysNss condition_%scs tˆƒS(N(sConditionSynchronizers identifier((s identifier(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysPscsˆS(N(s condition((s condition(s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysQs( s has_flocksFalses use_filess Synchronizers conditionsssync_gets identifierssyncssselfs _get_impls condition(sselfs identifiers use_filesslock_dirsdigest_filenamesssyncss condition((s identifierslock_dirsdigest_filenamess conditionssyncss:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__Hs %cCs|iƒiƒdS(N(sselfs _get_implsrelease_read_lock(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease_read_lockSscCs|iƒid|ƒSdS(Nswait(sselfs _get_implsacquire_read_lockswait(sselfswait((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysacquire_read_lockVscCs|iƒid|ƒSdS(Nswait(sselfs _get_implsacquire_write_lockswait(sselfswait((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysacquire_write_lockYscCs|iƒiƒdS(N(sselfs _get_implsrelease_write_lock(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease_write_lock\s(s__name__s __module__s__doc__sutilsWeakValuedRegistrys conditionssNonesFalsesTrues__init__srelease_read_locksacquire_read_locksacquire_write_locksrelease_write_lock(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys SynchronizerCs     s SyncStatecBstZdZd„ZRS(s]used to track the current thread's reading/writing state as well as reentrant block counting.cCsd|_t|_t|_dS(Ni(sselfsreentrantcountsFalseswritingsreading(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__bs  (s__name__s __module__s__doc__s__init__(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys SyncState_s sSynchronizerImplcBs\tZdZd„Zed„Zd„Zed„Zd„Zd„Z d„Z d„Z RS( s¦base class for synchronizers. the release/acquire methods may or may not be threadsafe depending on whether the 'state' accessor returns a thread-local instance.cCsx|i}|iotdƒ‚n|i otdƒ‚n|idjo|iƒt|_n|id8_dS(Nslock is in writing stateslock is not in reading statei(sselfsstateswritings LockErrorsreadingsreentrantcountsdo_release_read_locksFalse(sselfsstate((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease_read_lockks     cCs™|i}|iotdƒ‚n|idjoA|i|ƒ}|p|o|id7_t|_ n|Sn"|i o|id7_tSndS(Nslock is in writing stateii( sselfsstateswritings LockErrorsreentrantcountsdo_acquire_read_lockswaitsxsTruesreading(sselfswaitsstatesx((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysacquire_read_lockws    cCsx|i}|iotdƒ‚n|i otdƒ‚n|idjo|iƒt|_n|id8_dS(Nslock is in reading stateslock is not in writing statei(sselfsstatesreadings LockErrorswritingsreentrantcountsdo_release_write_locksFalse(sselfsstate((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease_write_lock†s     cCs™|i}|iotdƒ‚n|idjoA|i|ƒ}|p|o|id7_t|_ n|Sn"|i o|id7_tSndS(Nslock is in reading stateii( sselfsstatesreadings LockErrorsreentrantcountsdo_acquire_write_lockswaitsxsTrueswriting(sselfswaitsstatesx((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysacquire_write_lock’s    cCs tƒ‚dS(N(sNotImplementedError(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_read_lock¡scCs tƒ‚dS(N(sNotImplementedError(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_read_lock¤scCs tƒ‚dS(N(sNotImplementedError(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_write_lock§scCs tƒ‚dS(N(sNotImplementedError(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_write_lockªs( s__name__s __module__s__doc__srelease_read_locksTruesacquire_read_locksrelease_write_locksacquire_write_locksdo_release_read_locksdo_acquire_read_locksdo_release_write_locksdo_acquire_write_lock(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysSynchronizerImplgs      sFileSynchronizercBsVtZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z RS( s0a synchronizer using lock files. as it relies upon flock, its inherently not threadsafe. The Synchronizer container will maintain a unique FileSynchronizer per Synchronizer instance per thread. This works out since the synchronizers are all locking on a file on the filesystem. cCsitƒ|_|tjotiƒ}n|}ti||gddd|ƒ|_ t |_ t|_dS(Ns extensions.locksdigest(s SyncStatesselfsstateslock_dirsNonestempfiles gettempdirsutils encoded_paths identifiersdigest_filenamessfilenamesFalsesopenedsfiledesc(sselfs identifierslock_dirsdigest_filenames((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__µs  $ cCs4|i o%ti|i|ƒ|_t|_ndS(N(sselfsopenedsossopensfilenamesmodesfiledescsTrue(sselfsmode((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys_openÂs cCsˆ|ititiBƒ| oKy'ti|iti ti Bƒt }Wnt j o t}nX|Snti|iti ƒt SdS(N(sselfs_opensossO_CREATsO_RDONLYswaitsfcntlsflocksfiledescsLOCK_SHsLOCK_NBsTruesretsIOErrorsFalse(sselfswaitsret((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_read_lockÇs  cCsˆ|ititiBƒ| oKy'ti|iti ti Bƒt }Wnt j o t}nX|Snti|iti ƒt SdS(N(sselfs_opensossO_CREATsO_WRONLYswaitsfcntlsflocksfiledescsLOCK_EXsLOCK_NBsTruesretsIOErrorsFalse(sselfswaitsret((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_write_lock×s  cCs|iƒdS(N(sselfsrelease_all_locks(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_read_lockæscCs|iƒdS(N(sselfsrelease_all_locks(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_write_lockéscCsA|io3ti|itiƒti|iƒt|_ndS(N( sselfsopenedsfcntlsflocksfiledescsLOCK_UNsossclosesFalse(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysrelease_all_locksìs cCs[t odSnti|itiƒo.yti|iƒWqWtj oqWXndS(N(sossaccesssselfsfilenamesF_OKsremovesOSError(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__del__òs( s__name__s __module__s__doc__s__init__s_opensdo_acquire_read_locksdo_acquire_write_locksdo_release_read_locksdo_release_write_locksrelease_all_lockss__del__(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysFileSynchronizer­s       sConditionSynchronizercBsPtZdZd„Zed„ƒZed„Zd„Zed„Z d„Z RS(sïa synchronizer using a Condition. this synchronizer is based on threading.Lock() objects and therefore must be shared among threads, so it is also threadsafe. the "state" variable referenced by the base SynchronizerImpl class is turned into a thread local, and all the do_XXXX methods are synchronized on the condition object. The Synchronizer container will maintain a registry of ConditionSynchronizer objects keyed to the name of the synchronizer. cCsFtidd„ƒ|_d|_t|_titi ƒƒ|_ dS(NscreatorcCstƒS(N(s SyncState(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys si( sutils ThreadLocalsselfs tlocalstatesasyncsNonescurrent_sync_operations _threadings ConditionsLocks condition(sselfs identifier((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys__init__ s  cCs |iƒS(N(sselfs tlocalstate(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysscCs’|iiƒ|o)xK|itj o|iiƒqWn&|itj o|iiƒtSn|id7_|iiƒ| ot SndS(Ni( sselfs conditionsacquireswaitscurrent_sync_operationsNonesreleasesFalsesasyncsTrue(sselfswait((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_read_locks   cCs‚|iiƒ|id8_|idjo%|itj o|iiƒqqn!|idjotdƒ‚n|iiƒdS(Niis7Synchronizer error - too many release_read_locks called( sselfs conditionsacquiresasyncscurrent_sync_operationsNones notifyAlls LockErrorsrelease(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_read_lock-s cCsØ|iiƒ|o)xK|itj o|iiƒqWn&|itj o|iiƒtSnti ƒ|_|i djo6|o|iiƒq·t|_|iiƒtSn|iiƒ| ot SndS(Ni( sselfs conditionsacquireswaitscurrent_sync_operationsNonesreleasesFalses _threadings currentThreadsasyncsTrue(sselfswait((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_acquire_write_lock?s$     cCsZ|iiƒ|itiƒjotdƒ‚nt|_|iiƒ|ii ƒdS(Ns>Synchronizer error - current thread doesnt have the write lock( sselfs conditionsacquirescurrent_sync_operations _threadings currentThreads LockErrorsNones notifyAllsrelease(sself((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysdo_release_write_lockds    ( s__name__s __module__s__doc__s__init__spropertysstatesTruesdo_acquire_read_locksdo_release_read_locksdo_acquire_write_locksdo_release_write_lock(((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pysConditionSynchronizerþs     %(s__all__sosssysstempfilesthreads_threads threadings _threadings ImportErrors dummy_threadsdummy_threadingsgetwindowsversionsFalses has_flocksfcntlsTruesbeakersutilsbeaker.exceptionss LockErrorsobjectsNameLocks Synchronizers SyncStatesSynchronizerImplsFileSynchronizersConditionSynchronizer(sfcntlsutils_threadsSynchronizerImpls__all__s _threadingstempfilesConditionSynchronizers has_flocksNameLocks Synchronizerssyss LockErrorsFileSynchronizersoss SyncState((s:build/bdist.darwin-8.0.1-x86/egg/beaker/synchronization.pys?s4            'FQPKT#68ø‡3i©©beaker/middleware.pyc;ò €LäFc@s¡y/dklZeddƒZeddƒZWneZeZnXdklZdkl Z defd„ƒYZde fd „ƒYZ d „Z d „Z d S( (sStackedObjectProxysnamesBeaker Sessions Cache Manager(sCacheMiddleware(sSessionMiddlewaresCacheMiddlewarecBstZeZeZRS(N(s__name__s __module__sFalses deprecateds beaker_cachescache(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pysCacheMiddleware ssSessionMiddlewarecBstZeZeZRS(N(s__name__s __module__sFalses deprecatedsbeaker_sessionssession(((s5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pysSessionMiddlewaresc s‡‡d†}|SdS(Ncst|ˆˆSdS(N(sSessionMiddlewaresapps global_confskwargs(sapp(s global_confskwargs(s5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pysfilters(sfilter(s global_confskwargssfilter((s global_confskwargss5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pyssession_filter_factoryscKst|||SdS(N(sSessionMiddlewaresapps global_confskwargs(sapps global_confskwargs((s5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pyssession_filter_app_factorysN( spaste.registrysStackedObjectProxysbeaker_sessions beaker_cachesNones beaker.cachesCacheMiddlewaresDeprecatedCacheMiddlewaresbeaker.sessionsSessionMiddlewaresDeprecatedSessionMiddlewaressession_filter_factoryssession_filter_app_factory( ssession_filter_app_factorysCacheMiddlewares beaker_cachessession_filter_factorysDeprecatedSessionMiddlewaresSessionMiddlewaresStackedObjectProxysbeaker_sessionsDeprecatedCacheMiddleware((s5build/bdist.darwin-8.0.1-x86/egg/beaker/middleware.pys?s     PKS#68R™êIÖÖbeaker/converters.pyc;ò €LäFc@sd„Zeed„ZdS(cCs˜t|ttfƒot|iƒiƒ}|ddddddgjotSqŠ|ddd d d d gjotSqŠtd |ƒ‚nt |ƒSdS(Nstruesyessonsysts1sfalsesnosoffsnsfs0sString is not true/false: %r( s isinstancesobjsstrsunicodesstripslowersTruesFalses ValueErrorsbool(sobj((s5build/bdist.darwin-8.0.1-x86/egg/beaker/converters.pysasboolscCs£t|ttfƒoO|i|ƒ}|o1gi}|D]}||iƒƒq:~}n|Sn;t|t t fƒo|Sn|t jogSn|gSdS(N(s isinstancesobjsstrsunicodessplitssepslstsstripsappends_[1]svsliststuplesNone(sobjssepsstripsvs_[1]slst((s5build/bdist.darwin-8.0.1-x86/egg/beaker/converters.pysaslists1 N(sasboolsNonesTruesaslist(saslistsasbool((s5build/bdist.darwin-8.0.1-x86/egg/beaker/converters.pys?s PK¤rJ7çÙeçÁ9Á9beaker/session.pyimport Cookie from datetime import datetime, timedelta import hmac import md5 import os import random import re import sys import time import UserDict import warnings try: from paste.registry import StackedObjectProxy beaker_session = StackedObjectProxy(name="Beaker Session") except: beaker_session = None from beaker.container import namespace_registry from beaker.util import coerce_session_params __all__ = ['SignedCookie', 'Session'] class SignedCookie(Cookie.BaseCookie): "extends python cookie to give digital signature support" def __init__(self, secret, input=None): self.secret = secret Cookie.BaseCookie.__init__(self, input) def value_decode(self, val): sig = val[0:32] value = val[32:] if hmac.new(self.secret, value).hexdigest() != sig: return None, val return val[32:], val def value_encode(self, val): return val, ("%s%s" % (hmac.new(self.secret, val).hexdigest(), val)) class Session(UserDict.DictMixin): "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, secret=None, log_file=None, namespace_class=None, **kwargs): if type is None: if data_dir is None: self.type = 'memory' else: self.type = 'file' else: self.type = type if namespace_class is None: self.namespace_class = namespace_registry(self.type) else: self.namespace_class = namespace_class self.kwargs = kwargs self.request = request self.data_dir = data_dir self.key = key self.timeout = timeout self.use_cookies = use_cookies self.cookie_expires = cookie_expires self.log_file = log_file self.was_invalidated = False self.secret = secret self.id = id if self.use_cookies: try: cookieheader = request['cookie'] except KeyError: cookieheader = '' if secret is not None: try: self.cookie = SignedCookie(secret, input = cookieheader) except Cookie.CookieError: self.cookie = SignedCookie(secret, input = None) else: self.cookie = Cookie.SimpleCookie(input = cookieheader) if self.id is None and self.cookie.has_key(self.key): self.id = self.cookie[self.key].value if self.id is None: self._create_id() else: self.is_new = False if not self.is_new: try: self.load() except: if invalidate_corrupt: self.invalidate() else: raise else: self.dict = {} def _create_id(self): self.id = md5.new( md5.new("%f%s%f%d" % (time.time(), id({}), random.random(), os.getpid()) ).hexdigest(), ).hexdigest() self.is_new = True if self.use_cookies: self.cookie[self.key] = self.id self.cookie[self.key]['path'] = '/' if self.cookie_expires is not True: if self.cookie_expires is False: expires = datetime.fromtimestamp( 0x7FFFFFFF ) elif isinstance(self.cookie_expires, timedelta): expires = datetime.today() + self.cookie_expires elif isinstance(self.cookie_expires, datetime): expires = self.cookie_expires else: raise ValueError("Invalid argument for cookie_expires: %s" % repr(self.cookie_expires)) self.cookie[self.key]['expires'] = \ expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" ) self.request['cookie_out'] = self.cookie[self.key].output(header='') self.request['set_cookie'] = False created = property(lambda self: self.dict['_creation_time']) def delete(self): """deletes the persistent storage for this session, but remains valid. """ self.namespace.acquire_write_lock() try: self.namespace.remove() finally: self.namespace.release_write_lock() def __getitem__(self, key): return self.dict.__getitem__(key) def __setitem__(self, key, value): self.dict.__setitem__(key, value) def __delitem__(self, key): del self.dict[key] def keys(self): return self.dict.keys() def __contains__(self, key): return self.dict.has_key(key) def has_key(self, key): return self.dict.has_key(key) def __iter__(self): return iter(self.dict.keys()) def iteritems(self): return self.dict.iteritems() def invalidate(self): "invalidates this session, creates a new session id, returns to the is_new state" namespace = self.namespace namespace.acquire_write_lock() try: namespace.remove() finally: namespace.release_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 = self.namespace_class(self.id, data_dir=self.data_dir, digest_filenames=False, **self.kwargs) namespace = self.namespace self.request['set_cookie'] = True namespace.acquire_write_lock() try: self.debug("session loading keys") self.dict = {} now = time.time() if not namespace.has_key('_creation_time'): namespace['_creation_time'] = now self.is_new = True try: self.accessed = namespace['_accessed_time'] namespace['_accessed_time'] = now except KeyError: namespace['_accessed_time'] = self.accessed = now if self.timeout is not None and now - self.accessed > self.timeout: self.invalidate() else: for k in namespace.keys(): self.dict[k] = namespace[k] finally: namespace.release_write_lock() def save(self): "saves the data for this session to persistent storage" if not hasattr(self, 'namespace'): curdict = self.dict self.load() self.dict = curdict self.namespace.acquire_write_lock() try: self.debug("session saving keys") todel = [] for k in self.namespace.keys(): if not self.dict.has_key(k): todel.append(k) for k in todel: del self.namespace[k] for k in self.dict.keys(): self.namespace[k] = self.dict[k] self.namespace['_accessed_time'] = self.dict['_accessed_time'] \ = time.time() self.namespace['_creation_time'] = self.dict['_creation_time'] \ = time.time() finally: self.namespace.release_write_lock() if self.is_new: self.request['set_cookie'] = True def lock(self): """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. """ self.namespace.acquire_write_lock() def unlock(self): """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. """ self.namespace.release_write_lock() def debug(self, message): if self.log_file is not None: self.log_file.write(message) 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. """ def __init__(self, environ, **params): self.__dict__['_params'] = params self.__dict__['_environ'] = environ self.__dict__['_sess'] = None self.__dict__['_headers'] = [] def _session(self): """Lazy initial creation of session object""" if self.__dict__['_sess'] is None: params = self.__dict__['_params'] environ = self.__dict__['_environ'] self.__dict__['_headers'] = req = {'cookie_out':None} req['cookie'] = environ.get('HTTP_COOKIE') self.__dict__['_sess'] = Session(req, use_cookies=True, **params) return self.__dict__['_sess'] def __getattr__(self, attr): return getattr(self._session(), attr) def __setattr__(self, attr, value): setattr(self._session(), attr, value) def __delattr__(self, name): self._session().__delattr__(name) def __getitem__(self, key): return self._session()[key] def __setitem__(self, key, value): self._session()[key] = value def __delitem__(self, key): self._session().__delitem__(key) def __repr__(self): return self._session().__repr__() def __iter__(self): """Only works for proxying to a dict""" return iter(self._session().keys()) def __contains__(self, key): return self._session().has_key(key) def get_by_id(self, id): params = self.__dict__['_params'] session = Session({}, use_cookies=False, id=id, **params) if session.is_new: session.namespace.remove() return None return session class SessionMiddleware(object): deprecated = True session = beaker_session 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.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. ``environ_key`` 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`` """ if self.deprecated: warnings.warn('SessionMiddleware is moving to beaker.middleware in ' '0.8', DeprecationWarning, 2) config = config or {} # Load up the default params self.options = dict(invalidate_corrupt=True, type=None, data_dir=None, key='beaker.session.id', timeout=None, secret=None, log_file=None) # Pull out any config args meant for beaker session. if there are any for dct in [config, kwargs]: for key, val in dct.iteritems(): if key.startswith('beaker.session.'): self.options[key[15:]] = val if key.startswith('session.'): self.options[key[8:]] = val if key.startswith('session_'): warnings.warn('Session options should start with session. ' 'instead of session_.', DeprecationWarning, 2) self.options[key[8:]] = val # Coerce and validate session params coerce_session_params(self.options) # Assume all keys are intended for cache if none are prefixed with 'cache.' if not self.options and config: self.options = config self.options.update(kwargs) self.wrap_app = wrap_app self.environ_key = environ_key def __call__(self, environ, start_response): session = SessionObject(environ, **self.options) if environ.get('paste.registry'): environ['paste.registry'].register(self.session, session) environ[self.environ_key] = session environ['beaker.get_session'] = self._get_session def session_start_response(status, headers, exc_info = None): if session.__dict__['_sess'] is not None: if session.__dict__['_headers']['set_cookie']: cookie = session.__dict__['_headers']['cookie_out'] if cookie: headers.append(('Set-cookie', cookie)) return start_response(status, headers, exc_info) try: response = self.wrap_app(environ, session_start_response) except: ty, val = sys.exc_info()[:2] if isinstance(ty, str): raise ty, val, sys.exc_info()[2] if ty.__name__ == 'HTTPFound' and \ session.__dict__['_sess'] is not None: cookie = session.__dict__['_headers']['cookie_out'] if cookie: val.headers.append(('Set-cookie', cookie)) raise ty, val, sys.exc_info()[2] else: return response def _get_session(self): return Session({}, use_cookies=False, **self.options) PKS#68–M;|T0T0beaker/util.pyc;ò €LäFc@skddddddgZydkZdkZWn%ej odkZdkZnXdklZl Z dk Z dk Z dk Z dk Z dkZy eZWn ej odklZnXd klZd „Zdefd „ƒYZdefd „ƒYZdefd „ƒYZdefd„ƒYZdded„Zd„Zd„Zd„Zd„Z dS(s ThreadLocalsRegistrysWeakValuedRegistrysSyncDicts encoded_pathsverify_directoryN(sdatetimes timedelta(sSet(sasboolcCsed}xXti|tiƒ o@y|d7}ti|dƒWq |djo‚q\q Xq WdS(scverifies and creates a directory. tries to ignore collisions with other threads and processes.iiièiN(striessossaccesssdirsF_OKsmakedirs(sdirstries((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysverify_directorys  cBs_tZdZeeed„Zd„Zd„Zd„Zd„Zd„Z d„Z d„Z RS( s$stores a value on a per-thread basiscCs7h|_||_||_|o|i|ƒndS(N(sselfsdictsdefaultscreatorsvaluesput(sselfsvaluesdefaultscreator((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__init__(s    cGs0t|ƒo|i|dƒn |iƒSdS(Ni(slensargsselfsputsget(sselfsarg((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__call__/s cCst|iƒƒSdS(N(sstrsselfsget(sself((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__str__5scCs||itiƒscOs„|iitiƒƒ oU|itj o|i|iƒqo|itj o|i|i||Žƒqon|itiƒSdS(N( sselfsdictshas_keys_threads get_identsdefaultsNonesputscreatorsargssparams(sselfsargssparams((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysgetAs !cCs|itiƒ=dS(N(sselfsdicts_threads get_ident(sself((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysremoveJs( s__name__s __module__s__doc__sNones__init__s__call__s__str__sassignsputsexistssgetsremove(((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys ThreadLocal&s       cBsztZdZd„Zd„Zed„Zed„Zed„Z d„Z d„Z d„Z d „Z d „Zd „ZRS( sÜ 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. 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. cCs||_||_dS(N(smutexsselfs dictionarysdict(sselfsmutexs dictionary((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__init__\s cCs|iiƒdS(N(sselfsdictsclear(sself((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysclear`scCsky>|i|ƒo|i|||ƒSn|i|||ƒSWn&tj o|i|||ƒSnXdS(s¼regular get method. returns the object asynchronously, if present and also passes the optional isvalidfunc, else defers to the synchronous get method which will create it.N(sselfshas_keyskeys_get_objs createfuncs isvalidfuncssync_getsKeyError(sselfskeys createfuncs isvalidfunc((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysgetcscCs|iiƒzkyA|i|ƒo|i|||dtƒSn|i ||ƒSWn#t j o|i ||ƒSnXWd|ii ƒXdS(Nscreate( sselfsmutexsacquireshas_keyskeys_get_objs createfuncs isvalidfuncsTrues_createsKeyErrorsrelease(sselfskeys createfuncs isvalidfunc((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pyssync_getos cCs_||}|tj o ||ƒ o2|o|i||ƒSq[|i|||ƒSn|SdS(N( sselfskeysobjs isvalidfuncsNonescreates_creates createfuncssync_get(sselfskeys createfuncs isvalidfuncscreatesobj((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys_get_obj|s  cCs|ƒ}|||<|SdS(N(s createfuncsobjsselfskey(sselfskeys createfuncsobj((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys_create†s  cCs|ii|ƒSdS(N(sselfsdictshas_keyskey(sselfskey((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pyshas_key‹scCs|ii|ƒSdS(N(sselfsdicts __contains__skey(sselfskey((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys __contains__scCs|ii|ƒSdS(N(sselfsdicts __getitem__skey(sselfskey((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys __getitem__scCs|ii||ƒdS(N(sselfsdicts __setitem__skeysvalue(sselfskeysvalue((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys __setitem__‘scCs|ii|ƒSdS(N(sselfsdicts __delitem__skey(sselfskey((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys __delitem__“s(s__name__s __module__s__doc__s__init__sclearsNonesgetssync_getsFalses_get_objs_createshas_keys __contains__s __getitem__s __setitem__s __delitem__(((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysSyncDictNs        cBstZdZd„ZRS(sa registry object.cCsti|tiƒhƒdS(N(sSyncDicts__init__sselfs _threadingsLock(sself((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__init__™s(s__name__s __module__s__doc__s__init__(((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysRegistry—s cBstZdZd„ZRS(sOa registry that stores objects only as long as someone has a reference to them.cCs#ti|tiƒtiƒƒdS(N(sSyncDicts__init__sselfs _threadingsRLocksweakrefsWeakValueDictionary(sself((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys__init__žs(s__name__s __module__s__doc__s__init__(((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysWeakValuedRegistryœs s.encic Cs ti|dƒ}|oti|ƒiƒ}ng}x+t d|ƒD]}|i |d|!ƒqHWt ii||Œ}t|ƒt ii|||ƒSdS(ssgenerate a unique file-accessible path from the given list of identifiers starting at the given root directory.s_iiN(sstringsjoins identifierssidentsdigestsshasnews hexdigeststokenssrangesdepthsdsappendsosspathsrootsdirsverify_directorys extension( sroots identifierss extensionsdepthsdigestsidentstokenssdirsd((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pys encoded_path¨s cCs­t||ƒ o”t|tƒ o |f}nt}xQ|D]I}y-|tjo t}n||ƒ}t }WnnX|oPq<q<W| ot |ƒ‚q¥n|SdS(N( s isinstancesoptstypesstuplesFalsescoercedstypsboolsasboolsTrues Exceptionserror(soptstypesserrorscoercedstyp((s/build/bdist.darwin-8.0.1-x86/egg/beaker/util.pysverify_options¹s$      cCsMxB|D]:\}}}||jot||||ƒ||…scCs3|iiƒz|iiƒWd|iiƒXdS(sDdeletes the persistent storage for this session, but remains valid. N(sselfs namespacesacquire_write_locksremovesrelease_write_lock(sself((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pysdelete‡s  cCs|ii|ƒSdS(N(sselfsdicts __getitem__skey(sselfskey((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys __getitem__scCs|ii||ƒdS(N(sselfsdicts __setitem__skeysvalue(sselfskeysvalue((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys __setitem__‘scCs|i|=dS(N(sselfsdictskey(sselfskey((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys __delitem__“scCs|iiƒSdS(N(sselfsdictskeys(sself((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pyskeys•scCs|ii|ƒSdS(N(sselfsdictshas_keyskey(sselfskey((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys __contains__—scCs|ii|ƒSdS(N(sselfsdictshas_keyskey(sselfskey((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pyshas_key™scCst|iiƒƒSdS(N(sitersselfsdictskeys(sself((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys__iter__›scCs|iiƒSdS(N(sselfsdicts iteritems(sself((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys iteritemsscCsP|i}|iƒz|iƒWd|iƒXt|_|iƒ|iƒdS(sOinvalidates this session, creates a new session id, returns to the is_new stateN( sselfs namespacesacquire_write_locksremovesrelease_write_locksTrueswas_invalidateds _create_idsload(sselfs namespace((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys invalidate s     cCsI|i|id|idt|i|_|i}t|id<|i ƒzí|i dƒh|_ t i ƒ}|idƒ o||ds    (s__name__s __module__s__doc__s__init__s_sessions __getattr__s __setattr__s __delattr__s __getitem__s __setitem__s __delitem__s__repr__s__iter__s __contains__s get_by_id(((s2build/bdist.darwin-8.0.1-x86/egg/beaker/session.pys SessionObject s           sSessionMiddlewarecBs5tZeZeZedd„Zd„Zd„Z RS(Nsbeaker.sessioncKsl|iotidtdƒn|ph}tdtdtdtdddtd td tƒ|_ x³||gD]¥}xœ|i ƒD]Ž\}}|id ƒo||i |d PKS#68È2×Þƒƒbeaker/__init__.pyc;ò €LäFc@sdS(N((((s3build/bdist.darwin-8.0.1-x86/egg/beaker/__init__.pys?sPKT#68ÀBÚßßbeaker/signedcookie.pyc;ò EüòFc@s[dZdkZdkZdkZdklZlZdklZdefd„ƒYZ dS(s Signed Cookie middleware supportN(sdatetimes timedelta(s SignedCookiesSignedCookieMiddlewarecBs&tZdeedd„Zd„ZRS(Nsbeaker_cookie.ids beaker.cookiecCs:||_||_||_||_||_||_dS(sCreate signed cookie middleware that loads into environ ``secret`` The secret to use for signing the session data. ``key`` Name to use for the data. ``timeout`` Time in seconds that the cookie data is considered valid for. ``cookie_expires`` Time in seconds that will be set from now for when the cookie expires. Set to True to expire at end of browser session or False to never expire. N(sappsselfssecretskeystimeoutscookie_expiress environ_name(sselfsappssecretskeystimeoutscookie_expiress environ_name((s7build/bdist.darwin-8.0.1-x86/egg/beaker/signedcookie.pys__init__ s     c s>tiˆidƒˆiddƒ}|iˆiƒ}t ‰|o|i d ‰|i d}ˆi t j oF|iddƒ\}}tiƒt|ƒˆi jo d}q³n|ˆˆi(sselfs __class__s__name__sstr(sself((s1build/bdist.darwin-8.0.1-x86/egg/beaker/cookie.pys__repr__Šs( s__name__s __module__s__doc__s metaCookies __metaclass__s DOWNGRADEsIGNOREs EXCEPTIONsparses classmethods__init__s__str__s__repr__(((s1build/bdist.darwin-8.0.1-x86/egg/beaker/cookie.pysCookieKs    s SignedCookiecBsPtZdZeid„ZeeƒZed„Zd„Z d„Z d„Z RS(sx This is a variation of Cookie that provides automatic cryptographic signing of cookies and verification. It uses the HMAC support in the Python standard library. This ensures that the cookie has not been tamprered with on the client side. Note that this class does not encrypt cookie data, thus it is still plainly visible as part of the cookie. c KsÒt|||}g}x—|D]}||}y|i|ƒWqt j o_|t i jo‚q®|t ijo|i|ƒq®t it i|ƒƒ|||[^;\ =]+)\ *(=\ *)?(?P"(?:[^\\"]|\\.)*"|[^;]*)\s*;?cCs”h}ti|ƒ}xt|D]l}|idƒ|idƒf\}}|ddjo |t jp ||jo|||ƒ|| self.timeout: val = '' environ[self.environ_name] = val else: cookie_id = md5.new(md5.new(os.urandom(128)).hexdigest()).hexdigest() environ[self.environ_name] = '' environ['beaker.cookie_id'] = cookie_id environ['beaker.cookie_obj'] = cookie def cap_start_response(status, headers, exc_info=None): user_data = environ[self.environ_name] data = ''.join([cookie_id, user_data]) cookie = environ['beaker.cookie_obj'] # If we have a cookie already, and the value is the same as the # data (its unchanged), and there's no timeout we don't need to # send it again if cookie and cookie.value == data and self.timeout is not None: return start_response(status, headers, exc_info) # If we have a timeout, set the time in the cookie if self.timeout: data = ''.join([cookie_id, str(time.time()) + '#' + user_data]) headers.append(("Cache-Control", 'no-cache="set-cookie"')) cookie = SignedCookie(self.key, data, self.secret) cookie.path = '/' if self.cookie_expires is not True: if self.cookie_expires is False: # No expiration, set it for the far future expires = datetime.fromtimestamp( 0x7FFFFFFF ) elif isinstance(self.cookie_expires, timedelta): # Set it for the time difference from today expires = datetime.today() + self.cookie_expires elif isinstance(self.cookie_expires, datetime): expires = self.cookie_expires cookie.set_expires(expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )) headers.append(('Set-Cookie', str(cookie))) return start_response(status, headers, exc_info) return self.app(environ, cap_start_response) PKR#68ÑñÔï6'6'beaker/ext/database.pyc;ò ™óFc@s"dkZdkZdklZdklZlZdklZlZdk l Z l Z dk l Z lZeZeieƒZy(dkZdkZdkiZdZWn,ej o dklZedƒ‚nXeed ƒ o d Znd efd „ƒYZd efd„ƒYZdS(N(sdatetime(sNamespaceManagers Container(sInvalidCacheBackendErrorsMissingCacheParameter(s Synchronizers _threading(sverify_directorysSyncDicts0.3(stypess8Database cache backend requires the 'sqlalchemy' librarys BoundMetaDatas0.4sDatabaseNamespaceManagercBs¼tZeeiƒhƒZeeiƒhƒZeeedeed„Z d„Z d„Z e d„Z d„Zd„Zd„Zd „Zd „Zd „Zd „Zd „Zd„ZRS(Ns beaker_cachec  sßti|||ˆtjo |‰n|tj o ||_n+|tjot dƒ‚n|d|_t |iƒˆpˆd‰ˆˆ} ‡‡‡d†} h|_t|_t|_tii| | ƒ|_dS(sCreates a database namespace manager ``url`` SQLAlchemy compliant db url ``sa_opts`` A dictionary of SQLAlchemy keyword options to initialize the engine with. ``optimistic`` Use optimistic session locking, note that this will result in an additional select when updating a cache value to compare version numbers. ``table_name`` The table name to use in the database for the cache. s data_dir or lock_dir is requireds/container_db_lockssa.urlcs刈}‡‡d†}tii||ƒ}ti ˆ|ti dt i dt ƒti dt idƒdtƒti dt idtƒti dt idtƒti d t iƒdtƒtidƒƒ}|id t ƒ|SdS( Ncs”tdjoNˆidƒoˆ otiˆds(sNamespaceManagers__init__sselfs namespacesparamsslock_dirsNonesdata_dirsMissingCacheParametersverify_directorysMemcachedNamespaceManagersclientssgetsurlsmc(sselfs namespacesurlsdata_dirslock_dirsparams((surls8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys__init__s     cCsdS(N((sself((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysdo_acquire_read_lock"scCsdS(N((sself((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysdo_release_read_lock#scCstSdS(N(sTrue(sselfswait((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysdo_acquire_write_lock$scCsdS(N((sself((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysdo_release_write_lock%scOsdS(N((sselfsargssparams((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysopen)scOsdS(N((sselfsargssparams((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysclose*scCsT|iddƒ}|ii|id|ƒ}|tjot|ƒ‚n|SdS(Ns s·s_( skeysreplacesselfsmcsgets namespacesvaluesNonesKeyError(sselfskeysvalue((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys __getitem__,s  cCs7|iddƒ}|ii|id|ƒtj SdS(Ns s·s_(skeysreplacesselfsmcsgets namespacesNone(sselfskey((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys __contains__3scCs7|iddƒ}|ii|id|ƒtj SdS(Ns s·s_(skeysreplacesselfsmcsgets namespacesNone(sselfskey((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pyshas_key7scCsˆ|iddƒ}|ii|idƒ}|tjo h}nt||<|ii |id|ƒ|ii |id||ƒdS(Ns s·s:keyss_( skeysreplacesselfsmcsgets namespaceskeyssNonesTruessetsvalue(sselfskeysvalueskeys((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys __setitem__;s   cCsˆ|iddƒ}|ii|idƒ}y@||=|ii|id|ƒ|ii|id|ƒWnt j o ‚nXdS(Ns s·s:keyss_( skeysreplacesselfsmcsgets namespaceskeyssdeletessetsKeyError(sselfskeyskeys((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys __delitem__DscCsq|ii|idƒ}|tj oGx)|D]!}|ii|id|ƒq-W|ii|idƒndS(Ns:keyss_(sselfsmcsgets namespaceskeyssNoneskeysdelete(sselfskeysskey((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys do_removeNs  cCsf|ii|idƒ}|tjogSn5gi}|iƒD]}||i dƒƒqB~SdS(Ns:keyss·( sselfsmcsgets namespaceskeyssNonesappends_[1]sxsreplace(sselfskeyss_[1]sx((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pyskeysUs (s__name__s __module__sSyncDicts _threadingsLocksclientssNones__init__sdo_acquire_read_locksdo_release_read_locksTruesdo_acquire_write_locksdo_release_write_locksopenscloses __getitem__s __contains__shas_keys __setitem__s __delitem__s do_removeskeys(((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysMemcachedNamespaceManagers          sMemcachedContainercBsAtZeed„Zd„ZeeƒZed„Zd„ZRS(NcKs t|_dS(N(sNonesselfsfunclock(sselfsdata_dirslock_dirsparams((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysdo_init^scKst|||SdS(N(sMemcachedNamespaceManagers namespacesurlsparams(sselfs namespacesurlsparams((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pyscreate_namespaceascCsV|itjo2tdd|iidtd|iiƒ|_n|ii|ƒSdS(Ns identifiersmemcachedcontainer/funclock/%ss use_filesslock_dir( sselfsfunclocksNones Synchronizersnamespacemanagers namespacesTrueslock_dirsacquire_write_lockswait(sselfswait((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pyslock_createfuncescCs|iiƒdS(N(sselfsfunclocksrelease_write_lock(sself((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysunlock_createfuncms( s__name__s __module__sNonesdo_initscreate_namespaces classmethodsTrueslock_createfuncsunlock_createfunc(((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pysMemcachedContainer\s    (ssyssbeaker.containersNamespaceManagers Containersbeaker.exceptionssInvalidCacheBackendErrorsMissingCacheParametersbeaker.synchronizations _threadings Synchronizers beaker.utilsverify_directorysSyncDicts cmemcachesmemcaches ImportErrorsMemcachedNamespaceManagersMemcachedContainer( s SynchronizersNamespaceManagers Containers _threadingsSyncDictssyssmemcachesMissingCacheParametersInvalidCacheBackendErrorsMemcachedContainersMemcachedNamespaceManagersverify_directory((s8build/bdist.darwin-8.0.1-x86/egg/beaker/ext/memcached.pys?s   LPKI#68a*¨ÄÄEGG-INFO/SOURCES.txt.hgignore .hgtags CHANGELOG LICENSE setup.cfg setup.py Beaker.egg-info/PKG-INFO Beaker.egg-info/SOURCES.txt Beaker.egg-info/dependency_links.txt Beaker.egg-info/entry_points.txt Beaker.egg-info/not-zip-safe Beaker.egg-info/top_level.txt beaker/__init__.py beaker/cache.py beaker/container.py beaker/converters.py beaker/cookie.py beaker/exceptions.py beaker/middleware.py beaker/session.py beaker/signedcookie.py beaker/synchronization.py beaker/util.py beaker/ext/__init__.py beaker/ext/database.py beaker/ext/memcached.py tests/test_base.py tests/test_cache.py tests/test_container.py tests/test_database.py tests/test_increment.py tests/test_memcached.py tests/test_syncdict.py tests/test_synchronizer.py PKG#68[¹„ÙÙEGG-INFO/entry_points.txt [paste.filter_factory] beaker_session = beaker.middleware:session_filter_factory [paste.filter_app_factory] beaker_session = beaker.middleware:session_filter_app_factory PKG#68“×2EGG-INFO/dependency_links.txt PKG#68P»  EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: Beaker Version: 0.8 Summary: A Session and Caching library with WSGI Middleware Home-page: http://beaker.groovie.org Author: Ben Bangart, Mike Bayer, Philip Jenvey Author-email: ben@groovie.org, pjenvey@groovie.org License: MIT Description: Cache and Session Library +++++++++++++++++++++++++ About ===== Beaker is a web session and general caching library that includes WSGI middleware for use in web applications. As a general caching library, Beaker can handle storing for various times any Python object that can be pickled with optional back-ends on a fine-grained basis. Beaker was built largely on the code from MyghtyUtils, then refactored and extended with database support. Beaker includes Cache and Session WSGI middleware to ease integration with WSGI capable frameworks, and is automatically used by `Pylons `_. Features ======== * Fast, robust performance * Multiple reader/single writer lock system to avoid duplicate simultaneous cache creation * Cache back-ends include dbm, file, memory, memcached, and database (Using SQLAlchemy for multiple-db vendor support) * Signed cookie's to prevent session hijacking/spoofing * Extensible Container object to support new back-ends * Cache's can be divided into namespaces (to represent templates, objects, etc.) then keyed for different copies * Create functions for automatic call-backs to create new cache copies after expiration * Fine-grained toggling of back-ends, keys, and expiration per Cache object Usage ===== Caching ------- Basic Example:: from beaker.cache import CacheManager cm = CacheManager(type='dbm', data_dir='./cache') cache = cm.get_cache('mytemplate') def somethingslow(): # slow stuff db_lookups() # Get the value, this will create the cache copy the first time # and any time it expires (in seconds, so 3600 = one hour) result = mycache.get_value(day, createfunc=somethingslow, expiretime=3600) Using WSGI:: from beaker.middleware import CacheMiddleware def simple_app(environ, start_response): cache = environ['beaker.cache'].get_cache('testcache') try: value = cache.get_value('value') except KeyError: value = 0 cache.set_value('value', value+1) start_response('200 OK', [('Content-type', 'text/plain')]) return ['The current value is: %s' % cache.get_value('value')] app = CacheMiddleware(simple_app, type='dbm', data_dir='./cache') Sessions -------- Using WSGI:: from beaker.middleware import SessionMiddleware def simple_app(environ, start_response): session = environ['beaker.session'] if not session.has_key('value'): session['value'] = 0 session['value'] += 1 session.save() start_response('200 OK', [('Content-type', 'text/plain')]) return ['The current value is: %d' % session['value']] wsgi_app = SessionMiddleware(simple_app, type='dbm', data_dir='./cache') Source ====== The latest developer version is available in a `Mercurial repository `_. Keywords: wsgi myghty session web cache middleware Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content PKG#68ÉÉ"EGG-INFO/top_level.txtbeaker PKq*7“×2EGG-INFO/not-zip-safe PKS#68ž&Šd¹¹¤beaker/exceptions.pycPKT#68·_L›&&¤ìbeaker/cache.pycPK:})7­Ø* - -¤5+beaker/synchronization.pyPK:})7€Œ¥¤ Ybeaker/__init__.pyPK:})7{í¼©žž¤>Ybeaker/util.pyPK:})7 ¸__¤wbeaker/converters.pyPKS#68°÷ú¼¨¼¨¤™zbeaker/container.pycPK:})7&w0Êʤ‡#beaker/exceptions.pyPKvzC7 ‘CgCg¤ƒ$beaker/container.pyPK‡47Ô÷Óáðð¤÷‹beaker/cookie.pyPKR#68ÒÀÞdGdG¤¬beaker/synchronization.pycPKT#68ø‡3i©©¤±óbeaker/middleware.pycPKS#68R™êIÖÖ¤übeaker/converters.pycPK¤rJ7çÙeçÁ9Á9¤–beaker/session.pyPKS#68–M;|T0T0¤†;beaker/util.pycPK:})7÷øïª[[¤lbeaker/middleware.pyPK:})7*V1VV¤”obeaker/cache.pyPKT#68sú½¼M¼M¤‰beaker/session.pycPKS#68È2×Þƒƒ¤×beaker/__init__.pycPKT#68ÀBÚßߤ·×beaker/signedcookie.pycPKS#68ýrÖ4®%®%¤Ëébeaker/cookie.pycPKp˜47·ZÄ1˜˜¤¨beaker/signedcookie.pyPKR#68ÑñÔï6'6'¤t beaker/ext/database.pycPK:})7¤ßGbeaker/ext/__init__.pyPK@£47T%  $$¤Hbeaker/ext/database.pyPKR#68{*t²‡‡¤kcbeaker/ext/__init__.pycPKò¸.71uÝ¡::¤'dbeaker/ext/memcached.pyPKR#68ÑBÅÉɤ–sbeaker/ext/memcached.pycPKI#68a*¨ÄĤ•’EGG-INFO/SOURCES.txtPKG#68[¹„ÙÙ¤‹•EGG-INFO/entry_points.txtPKG#68“×2¤›–EGG-INFO/dependency_links.txtPKG#68P»  ¤×–EGG-INFO/PKG-INFOPKG#68ÉÉ"¤&§EGG-INFO/top_level.txtPKq*7“×2¤a§EGG-INFO/not-zip-safePK""Ò•§