Commits

Lynn Rees  committed 01d4cc3

- reorg 0.4.1

  • Participants
  • Parent commits 1d096b6
  • Branches wsgistate

Comments (0)

Files changed (28)

+Changes between 0.4 and 0.4.1
+
+- only caches explicitly declared HTTP methods (Roberto De Alemeida)
+- non-destructively consumes 'wsgi.input' (Roberto De Alemeida)
+Session (flup-compatible), caching, memoizing, and HTTP
+cache control middleware for WSGI. Supports memory,
+filesystem, database, and memcached based backends.
+
+# Simple memoization example:
+
+from wsgistate.memory import memoize
+
+@memoize()
+def app(environ, start_response):
+    start_response('200 OK', [('Content-Type', 'text/plain')])
+    return ['Hello World!']
+
+if __name__ == '__main__':
+    from wsgiref.simple_server import make_server
+    http = make_server('', 8080, app)
+    http.serve_forever()
+
+# Simple session example:
+
+from wsgistate.memory import session
+
+@session()
+def app(environ, start_response):
+    session = environ['com.saddi.service.session'].session
+    count = session.get('count', 0) + 1
+    session['count'] = count
+    start_response('200 OK', [('Content-Type', 'text/plain')])
+    return ['You have been here %d times!' % count]
+
+if __name__ == '__main__':
+    from wsgiref.simple_server import make_server
+    http = make_server('', 8080, app)
+    http.serve_forever()
+#!python
+"""Bootstrap setuptools installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+    from ez_setup import use_setuptools
+    use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import sys
+DEFAULT_VERSION = "0.6c7"
+DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
+
+md5_data = {
+    'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
+    'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
+    'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
+    'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
+    'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
+    'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
+    'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
+    'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
+    'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
+    'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
+    'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
+    'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
+    'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
+    'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
+    'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
+    'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
+    'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
+    'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
+    'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
+    'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
+    'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
+    'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
+    'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
+    'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
+    'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
+    'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
+    'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
+}
+
+import sys, os
+
+def _validate_md5(egg_name, data):
+    if egg_name in md5_data:
+        from md5 import md5
+        digest = md5(data).hexdigest()
+        if digest != md5_data[egg_name]:
+            print >>sys.stderr, (
+                "md5 validation of %s failed!  (Possible download problem?)"
+                % egg_name
+            )
+            sys.exit(2)
+    return data
+
+
+def use_setuptools(
+    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+    download_delay=15
+):
+    """Automatically find/download setuptools and make it available on sys.path
+
+    `version` should be a valid setuptools version number that is available
+    as an egg for download under the `download_base` URL (which should end with
+    a '/').  `to_dir` is the directory where setuptools will be downloaded, if
+    it is not already available.  If `download_delay` is specified, it should
+    be the number of seconds that will be paused before initiating a download,
+    should one be required.  If an older version of setuptools is installed,
+    this routine will print a message to ``sys.stderr`` and raise SystemExit in
+    an attempt to abort the calling script.
+    """
+    try:
+        import setuptools
+        if setuptools.__version__ == '0.0.1':
+            print >>sys.stderr, (
+            "You have an obsolete version of setuptools installed.  Please\n"
+            "remove it from your system entirely before rerunning this script."
+            )
+            sys.exit(2)
+    except ImportError:
+        egg = download_setuptools(version, download_base, to_dir, download_delay)
+        sys.path.insert(0, egg)
+        import setuptools; setuptools.bootstrap_install_from = egg
+
+    import pkg_resources
+    try:
+        pkg_resources.require("setuptools>="+version)
+
+    except pkg_resources.VersionConflict, e:
+        # XXX could we install in a subprocess here?
+        print >>sys.stderr, (
+            "The required version of setuptools (>=%s) is not available, and\n"
+            "can't be installed while this script is running. Please install\n"
+            " a more recent version first.\n\n(Currently using %r)"
+        ) % (version, e.args[0])
+        sys.exit(2)
+
+def download_setuptools(
+    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+    delay = 15
+):
+    """Download setuptools from a specified location and return its filename
+
+    `version` should be a valid setuptools version number that is available
+    as an egg for download under the `download_base` URL (which should end
+    with a '/'). `to_dir` is the directory where the egg will be downloaded.
+    `delay` is the number of seconds to pause before an actual download attempt.
+    """
+    import urllib2, shutil
+    egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
+    url = download_base + egg_name
+    saveto = os.path.join(to_dir, egg_name)
+    src = dst = None
+    if not os.path.exists(saveto):  # Avoid repeated downloads
+        try:
+            from distutils import log
+            if delay:
+                log.warn("""
+---------------------------------------------------------------------------
+This script requires setuptools version %s to run (even to display
+help).  I will attempt to download it for you (from
+%s), but
+you may need to enable firewall access for this script first.
+I will start the download in %d seconds.
+
+(Note: if this machine does not have network access, please obtain the file
+
+   %s
+
+and place it in this directory before rerunning this script.)
+---------------------------------------------------------------------------""",
+                    version, download_base, delay, url
+                ); from time import sleep; sleep(delay)
+            log.warn("Downloading %s", url)
+            src = urllib2.urlopen(url)
+            # Read/write all in one block, so we don't create a corrupt file
+            # if the download is interrupted.
+            data = _validate_md5(egg_name, src.read())
+            dst = open(saveto,"wb"); dst.write(data)
+        finally:
+            if src: src.close()
+            if dst: dst.close()
+    return os.path.realpath(saveto)
+
+def main(argv, version=DEFAULT_VERSION):
+    """Install or upgrade setuptools and EasyInstall"""
+
+    try:
+        import setuptools
+    except ImportError:
+        egg = None
+        try:
+            egg = download_setuptools(version, delay=0)
+            sys.path.insert(0,egg)
+            from setuptools.command.easy_install import main
+            return main(list(argv)+[egg])   # we're done here
+        finally:
+            if egg and os.path.exists(egg):
+                os.unlink(egg)
+    else:
+        if setuptools.__version__ == '0.0.1':
+            # tell the user to uninstall obsolete version
+            use_setuptools(version)
+
+    req = "setuptools>="+version
+    import pkg_resources
+    try:
+        pkg_resources.require(req)
+    except pkg_resources.VersionConflict:
+        try:
+            from setuptools.command.easy_install import main
+        except ImportError:
+            from easy_install import main
+        main(list(argv)+[download_setuptools(delay=0)])
+        sys.exit(0) # try to force an exit
+    else:
+        if argv:
+            from setuptools.command.easy_install import main
+            main(argv)
+        else:
+            print "Setuptools version",version,"or greater has been installed."
+            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
+
+
+
+def update_md5(filenames):
+    """Update our built-in md5 registry"""
+
+    import re
+    from md5 import md5
+
+    for name in filenames:
+        base = os.path.basename(name)
+        f = open(name,'rb')
+        md5_data[base] = md5(f.read()).hexdigest()
+        f.close()
+
+    data = ["    %r: %r,\n" % it for it in md5_data.items()]
+    data.sort()
+    repl = "".join(data)
+
+    import inspect
+    srcfile = inspect.getsourcefile(sys.modules[__name__])
+    f = open(srcfile, 'rb'); src = f.read(); f.close()
+
+    match = re.search("\nmd5_data = {\n([^}]+)}", src)
+    if not match:
+        print >>sys.stderr, "Internal error!"
+        sys.exit(2)
+
+    src = src[:match.start(1)] + repl + src[match.end(1):]
+    f = open(srcfile,'w')
+    f.write(src)
+    f.close()
+
+
+if __name__=='__main__':
+    if len(sys.argv)>2 and sys.argv[1]=='--md5update':
+        update_md5(sys.argv[2:])
+    else:
+        main(sys.argv[1:])
+
+
+
+
+
+# Copyright (c) 2006 L. C. Rees.  All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# 1.  Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+# 2.  Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3.  Neither the name of the Portable Site Information Project nor the names
+# of its contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+'''setup - setuptools based setup for wsgistate.'''
+
+import ez_setup
+ez_setup.use_setuptools()
+
+try:
+    from setuptools import setup
+except:
+    from distutils.core import setup
+
+setup(name='wsgistate',
+      version='0.4.1',
+      description='''WSGI session and caching middleware.''',
+      long_description='''Session (flup-compatible), caching, memoizing, and HTTP cache control
+middleware for WSGI. Supports memory, filesystem, database, and memcached based backends.
+
+# Simple memoization example:
+
+from wsgistate.memory import memoize
+
+@memoize()
+def app(environ, start_response):
+    start_response('200 OK', [('Content-Type', 'text/plain')])
+    return ['Hello World!']
+
+if __name__ == '__main__':
+    from wsgiref.simple_server import make_server
+    http = make_server('', 8080, app)
+    http.serve_forever()
+
+# Simple session example:
+
+from wsgistate.memory import session
+
+@session()
+def app(environ, start_response):
+    session = environ['com.saddi.service.session'].session
+    count = session.get('count', 0) + 1
+    session['count'] = count
+    start_response('200 OK', [('Content-Type', 'text/plain')])
+    return ['You have been here %d times!\n' % count]
+
+if __name__ == '__main__':
+    from wsgiref.simple_server import make_server
+    http = make_server('', 8080, app)
+    http.serve_forever()''',
+      author='L. C. Rees',
+      author_email='lcrees@gmail.com',
+      license='BSD',
+      packages = ['wsgistate'],
+      test_suite='wsgistate.tests',
+      zip_safe = True,
+      keywords='WSGI session caching persistence memoizing HTTP Web',
+      classifiers=['Development Status :: 4 - Beta',
+                    'Environment :: Web Environment',
+                    'License :: OSI Approved :: BSD License',
+                    'Natural Language :: English',
+                    'Operating System :: OS Independent',
+                    'Programming Language :: Python',
+                    'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware'],
+      install_requires = ['SQLAlchemy'],)

File wsgistate/CHANGELOG

-Changes between 0.4 and 0.4.1
-
-- only caches explicitly declared HTTP methods (Roberto De Alemeida)
-- non-destructively consumes 'wsgi.input' (Roberto De Alemeida)

File wsgistate/README

-Session (flup-compatible), caching, memoizing, and HTTP
-cache control middleware for WSGI. Supports memory,
-filesystem, database, and memcached based backends.
-
-# Simple memoization example:
-
-from wsgistate.memory import memoize
-
-@memoize()
-def app(environ, start_response):
-    start_response('200 OK', [('Content-Type', 'text/plain')])
-    return ['Hello World!']
-
-if __name__ == '__main__':
-    from wsgiref.simple_server import make_server
-    http = make_server('', 8080, app)
-    http.serve_forever()
-
-# Simple session example:
-
-from wsgistate.memory import session
-
-@session()
-def app(environ, start_response):
-    session = environ['com.saddi.service.session'].session
-    count = session.get('count', 0) + 1
-    session['count'] = count
-    start_response('200 OK', [('Content-Type', 'text/plain')])
-    return ['You have been here %d times!' % count]
-
-if __name__ == '__main__':
-    from wsgiref.simple_server import make_server
-    http = make_server('', 8080, app)
-    http.serve_forever()

File wsgistate/__init__.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2005 Allan Saddi <allan@saddi.com>
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Base Cache class'''
+
+__all__ = ['BaseCache', 'db', 'file', 'memory', 'memcached', 'session', 'simple', 'cache']
+
+def synchronized(func):
+    '''Decorator to lock and unlock a method (Phillip J. Eby).
+
+    @param func Method to decorate
+    '''
+    def wrapper(self, *__args, **__kw):
+        self._lock.acquire()
+        try:
+            return func(self, *__args, **__kw)
+        finally:
+            self._lock.release()
+    wrapper.__name__ = func.__name__
+    wrapper.__dict__ = func.__dict__
+    wrapper.__doc__ = func.__doc__
+    return wrapper
+
+
+class BaseCache(object):
+
+    '''Base Cache class.'''    
+    
+    def __init__(self, *a, **kw):
+        super(BaseCache, self).__init__()
+        timeout = kw.get('timeout', 300)
+        try:
+            timeout = int(timeout)
+        except (ValueError, TypeError):
+            timeout = 300
+        self.timeout = timeout
+
+    def __getitem__(self, key):
+        '''Fetch a given key from the cache.'''
+        return self.get(key)
+
+    def __setitem__(self, key, value):
+        '''Set a value in the cache. '''
+        self.set(key, value)
+
+    def __delitem__(self, key):
+        '''Delete a key from the cache.'''
+        self.delete(key) 
+
+    def __contains__(self, key):
+        '''Tell if a given key is in the cache.'''
+        return self.get(key) is not None
+
+    def get(self, key, default=None):
+        '''Fetch a given key from the cache.  If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        raise NotImplementedError()
+
+    def set(self, key, value):
+        '''Set a value in the cache. 
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.        
+        '''
+        raise NotImplementedError()
+
+    def delete(self, key):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        raise NotImplementedError()
+
+    def get_many(self, keys):
+        '''Fetch a bunch of keys from the cache. Returns a dict mapping each
+        key in keys to its value.  If the given key is missing, it will be
+        missing from the response dict.
+
+        @param keys Keywords of items in cache.        
+        '''
+        d = dict()
+        for k in keys:
+            val = self.get(k)
+            if val is not None: d[k] = val
+        return d

File wsgistate/cache.py

+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice,
+#       this list of conditions and the following disclaimer.
+#
+#    2. Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of psilib nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''WSGI middleware for caching.'''
+
+import time
+import rfc822
+from StringIO import StringIO
+
+__all__ = ['WsgiMemoize', 'CacheHeader', 'memoize', 'public', 'private',
+    'nocache', 'nostore', 'notransform', 'revalidate', 'proxyrevalidate',
+    'maxage', 'smaxage', 'vary', 'modified']
+
+def getinput(environ):
+    '''Non-destructively retrieves wsgi.input value.'''
+    wsginput = environ['wsgi.input']
+    # Non-destructively fetch string value of wsgi.input
+    if hasattr(wsginput, 'getvalue'):
+        qs = wsginput.getvalue()
+    # Otherwise, read and reconstruct wsgi.input
+    else:
+        # Never read more than content length
+        clength = int(environ['CONTENT_LENGTH'])
+        qs = wsginput.read(clength)
+        environ['wsgi.input'] = StringIO(qs)
+    return qs
+
+def expiredate(seconds, value):
+    '''Expire date headers for cache control.
+
+    @param seconds Seconds
+    @param value Value for Cache-Control header
+    '''
+    now = time.time()
+    return {'Cache-Control':value % seconds, 'Date':rfc822.formatdate(now),
+        'Expires':rfc822.formatdate(now + seconds)}
+
+def memoize(cache, **kw):
+    '''Decorator for caching.'''
+    def decorator(application):
+        return WsgiMemoize(application, cache, **kw)
+    return decorator
+
+def control(application, value):
+    '''Generic setter for 'Cache-Control' headers.
+
+    @param application WSGI application
+    @param value 'Cache-Control' value
+    '''
+    headers = {'Cache-Control':value}
+    return CacheHeader(application, headers)
+
+def expire(application, value):
+    '''Generic setter for 'Cache-Control' headers + expiration info.
+
+    @param application WSGI application
+    @param value 'Cache-Control' value
+    '''
+    now = rfc822.formatdate()
+    headers = {'Cache-Control':value, 'Date':now, 'Expires':now}
+    return CacheHeader(application, headers)
+
+def age(value, second):
+    '''Generic setter for 'Cache-Control' headers + future expiration info.
+
+    @param value 'Cache-Control' value
+    @param seconds # of seconds a resource should be considered invalid in
+    '''
+    def decorator(application):
+        return CacheHeader(application, expiredate(second, value))
+    return decorator
+
+def public(application):
+    '''Response MAY be cached.'''
+    return control(application, 'public')
+
+def private(application):
+    '''Response intended for 1 user that MUST NOT be cached.'''
+    return expire(application, 'private')
+
+def nocache(application):
+    '''Response that a cache can't send without origin server revalidation.'''
+    now = rfc822.formatdate()
+    headers = {'Cache-Control':'no-cache', 'Pragma':'no-cache', 'Date':now,
+        'Expires':now}
+    return CacheHeader(application, headers)
+
+def nostore(application):
+    '''Response that MUST NOT be cached.'''
+    return expire(application, 'no-store')
+
+def notransform(application):
+    '''A cache must not modify the Content-Location, Content-MD5, ETag,
+    Last-Modified, Expires, Content-Encoding, Content-Range, and Content-Type
+    headers.
+    '''
+    return control(application, 'no-transform')
+
+def revalidate(application):
+    '''A cache must revalidate a response with the origin server.'''
+    return control(application, 'must-revalidate')
+
+def proxyrevalidate(application):
+    '''Shared caches must revalidate a response with the origin server.'''
+    return control(application, 'proxy-revalidate')
+
+def maxage(seconds):
+    '''Sets the maximum time in seconds a response can be cached.'''
+    return age('max-age=%d', seconds)
+
+def smaxage(seconds):
+    '''Sets the maximum time in seconds a shared cache can store a response.'''
+    return age('s-maxage=%d', seconds)
+
+def expires(seconds):
+    '''Sets the time a response expires from the cache (HTTP 1.0).'''
+    headers = {'Expires':rfc822.formatdate(time.time() + seconds)}
+    def decorator(application):
+        return CacheHeader(application, headers)
+    return decorator
+
+def vary(headers):
+    '''Sets which fields allow a cache to use a response without revalidation.'''
+    headers = {'Vary':', '.join(headers)}
+    def decorator(application):
+        return CacheHeader(application, headers)
+    return decorator
+
+def modified(seconds=None):
+    '''Sets the time a response was modified.'''
+    headers = {'Modified':rfc822.formatdate(seconds)}
+    def decorator(application):
+        return CacheHeader(application, headers)
+    return decorator
+
+
+class CacheHeader(object):
+
+    '''Controls HTTP Cache Control headers.'''
+
+    def __init__(self, application, headers):
+        self.application = application
+        self.headers = headers
+
+    def __call__(self, environ, start_response):
+        # Restrict cache control to GET and HEAD per HTTP 1.1 RFC
+        if environ.get('REQUEST_METHOD') in ('GET', 'HEAD'):
+            # Co-routine to add cache control headers
+            def hdr_response(status, headers, exc_info=None):
+                theaders = self.headers.copy()
+                # Aggregate all 'Cache-Control' directives
+                if 'Cache-Control' in theaders:
+                    for idx, i in enumerate(headers):
+                        if i[0] != 'Cache-Control': continue
+                        curval = theaders.pop('Cache-Control')
+                        newval = ', '.join([curval, i[1]])
+                        headers.append(('Cache-Control', newval))
+                        del headers[idx]
+                        break
+                headers.extend((k, v) for k, v in theaders.iteritems())
+                return start_response(status, headers, exc_info)
+            return self.application(environ, hdr_response)
+        return self.application(environ, start_response)
+
+
+class WsgiMemoize(object):
+
+    '''WSGI middleware for response memoizing.'''
+
+    def __init__(self, app, cache, **kw):
+        self.application, self._cache = app, cache
+        # Adds method to cache key
+        self._methkey = kw.get('key_methods', False)
+        # Adds user submitted data to cache key
+        self._userkey = kw.get('key_user_info', False)
+        # Which HTTP responses by method are cached
+        self._allowed = kw.get('allowed_methods', set(['GET', 'HEAD']))
+
+    def __call__(self, environ, start_response):
+        # Verify requested response is cacheable
+        if environ['REQUEST_METHOD'] not in self._allowed:
+            return self.application(environ, start_response)
+        # Generate cache key
+        key = self._keygen(environ)
+        # Query cache for key prescence
+        info = self._cache.get(key)
+        # Return cached data
+        if info is not None:
+            start_response(info['status'], info['headers'], info['exc_info'])
+            return info['data']
+        # Cache start_response info
+        def cache_response(status, headers, exc_info=None):
+            # Add HTTP cache control headers
+            newhdrs = expiredate(self._cache.timeout, 's-maxage=%d')
+            headers.extend((k, v) for k, v in newhdrs.iteritems())
+            cachedict = {'status':status, 'headers':headers, 'exc_info':exc_info}
+            self._cache.set(key, cachedict)
+            return start_response(status, headers, exc_info)
+        # Wrap data in list to trigger iterator (Roberto De Alemeida)
+        data = list(self.application(environ, cache_response))
+        # Fetch cached dictionary
+        info = self._cache.get(key)
+        # Store in dictionary
+        info['data'] = data
+        # Store in cache
+        self._cache.set(key, info)
+        # Return data as response to intial request
+        return data
+
+    def _keygen(self, environ):
+        '''Generates cache keys.'''
+        # Base of key is always path of request
+        key = [environ['PATH_INFO']]
+        # Add method name to key if configured that way
+        if self._methkey: key.append(environ['REQUEST_METHOD'])
+        # Add user submitted data to string if configured that way
+        if self._userkey:
+            qs = environ.get('QUERY_STRING', '')
+            if qs != '':
+                key.append(qs)
+            else:
+                win = getinput(environ)
+                if win != '': key.append(win)
+        return ''.join(key)

File wsgistate/db.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Database cache backend.'''
+
+import time
+from datetime import datetime
+try:
+    from sqlalchemy import *
+except ImportError:
+    raise ImportError('DbCache module requires the SQLAlchemy package ' \
+        'from http://www.sqlalchemy.org/')
+from wsgistate import BaseCache
+from wsgistate.cache import WsgiMemoize
+from wsgistate.session import CookieSession, URLSession, SessionCache
+
+__all__ = ['DbCache', 'memoize', 'session', 'urlsession']
+
+
+def memoize(initstr, **kw):
+    '''Decorator for caching.
+
+    @param initstr Database initialization string
+    '''
+    def decorator(application):
+        _db_memo_cache = DbCache(initstr, **kw)
+        return WsgiMemoize(application, _db_memo_cache, **kw)
+    return decorator
+
+def session(initstr, **kw):
+    '''Decorator for sessions.
+
+    @param initstr Database initialization string
+    '''
+    def decorator(application):
+        _db_base_cache = DbCache(initstr, **kw)
+        _db_session_cache = SessionCache(_db_base_cache, **kw)
+        return CookieSession(application, _db_session_cache, **kw)
+    return decorator
+
+def urlsession(initstr, **kw):
+    '''Decorator for URL encoded sessions.
+
+    @param initstr Database initialization string
+    '''
+    def decorator(application):
+        _db_ubase_cache = DbCache(initstr, **kw)
+        _db_url_cache = SessionCache(_db_ubase_cache, **kw)
+        return URLSession(application, _db_url_cache, **kw)
+    return decorator
+
+
+class DbCache(BaseCache):     
+
+    '''Database cache backend.'''
+
+    def __init__(self, *a, **kw):
+        super(DbCache, self).__init__(self, *a, **kw)
+        # Get table name
+        tablename = kw.get('tablename', 'cache')
+        # Bind metadata
+        self._metadata = BoundMetaData(a[0])
+        # Make cache
+        self._cache = Table(tablename, self._metadata,
+            Column('id', Integer, primary_key=True, nullable=False, unique=True),
+            Column('key', String(60), nullable=False),
+            Column('value', PickleType, nullable=False),
+            Column('expires', DateTime, nullable=False))
+        # Create cache if it does not exist
+        if not self._cache.exists(): self._cache.create()
+        # Maximum number of entries to cull per call if cache is full
+        self._maxcull = kw.get('maxcull', 10)                
+        max_entries = kw.get('max_entries', 300)
+        try:
+            self._max_entries = int(max_entries)
+        except (ValueError, TypeError):
+            self._max_entries = 300
+
+    def __len__(self):
+        return self._cache.count().execute().fetchone()[0]
+
+    def get(self, k, default=None):
+        '''Fetch a given key from the cache.  If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        row = self._cache.select().execute(key=k).fetchone()
+        if row is None: return default
+        if row.expires < datetime.now().replace(microsecond=0):
+            self.delete(k)
+            return default
+        return row.value
+
+    def set(self, k, v):
+        '''Set a value in the cache.
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.      
+        '''
+        if len(self) > self._max_entries: self._cull()
+        timeout, cache = self.timeout, self._cache
+        # Get expiration time
+        exp = datetime.fromtimestamp(time.time() + timeout).replace(microsecond=0)        
+        #try:
+        # Update database if key already present
+        if k in self:
+            cache.update(cache.c.key==k).execute(value=v, expires=exp)
+        # Insert new key if key not present
+        else:            
+            cache.insert().execute(key=k, value=v, expires=exp)
+        # To be threadsafe, updates/inserts are allowed to fail silently
+        #except: pass
+       
+    def delete(self, k):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        self._cache.delete(self._cache.c.key==k).execute()
+
+    def _cull(self):
+        '''Remove items in cache to make more room.'''        
+        cache, maxcull = self._cache, self._maxcull
+        # Remove items that have timed out
+        now = datetime.now().replace(microsecond=0)
+        cache.delete(cache.c.expires < now).execute()
+        # Remove any items over the maximum allowed number in the cache
+        if len(self) >= self._max_entries:
+            # Upper limit for key query
+            ul = maxcull * 2
+            # Get list of keys
+            keys = [i[0] for i in select([cache.c.key], limit=ul).execute().fetchall()]
+            # Get some keys at random
+            delkeys = list(random.choice(keys) for i in range(maxcull))
+            # Delete keys
+            fkeys = tuple({'key':k} for k in delkeys)
+            cache.delete(cache.c.key.in_(bindparam('key'))).execute(*fkeys)

File wsgistate/ez_setup.py

-#!python
-"""Bootstrap setuptools installation
-
-If you want to use setuptools in your package's setup.py, just include this
-file in the same directory with it, and add this to the top of your setup.py::
-
-    from ez_setup import use_setuptools
-    use_setuptools()
-
-If you want to require a specific version of setuptools, set a download
-mirror, or use an alternate download directory, you can do so by supplying
-the appropriate options to ``use_setuptools()``.
-
-This file can also be run as a script to install or upgrade setuptools.
-"""
-import sys
-DEFAULT_VERSION = "0.6c7"
-DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
-
-md5_data = {
-    'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
-    'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
-    'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
-    'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
-    'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
-    'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
-    'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
-    'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
-    'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
-    'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
-    'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
-    'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
-    'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
-    'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
-    'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
-    'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
-    'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
-    'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
-    'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
-    'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
-    'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
-    'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
-    'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
-    'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
-    'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
-    'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
-    'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
-}
-
-import sys, os
-
-def _validate_md5(egg_name, data):
-    if egg_name in md5_data:
-        from md5 import md5
-        digest = md5(data).hexdigest()
-        if digest != md5_data[egg_name]:
-            print >>sys.stderr, (
-                "md5 validation of %s failed!  (Possible download problem?)"
-                % egg_name
-            )
-            sys.exit(2)
-    return data
-
-
-def use_setuptools(
-    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
-    download_delay=15
-):
-    """Automatically find/download setuptools and make it available on sys.path
-
-    `version` should be a valid setuptools version number that is available
-    as an egg for download under the `download_base` URL (which should end with
-    a '/').  `to_dir` is the directory where setuptools will be downloaded, if
-    it is not already available.  If `download_delay` is specified, it should
-    be the number of seconds that will be paused before initiating a download,
-    should one be required.  If an older version of setuptools is installed,
-    this routine will print a message to ``sys.stderr`` and raise SystemExit in
-    an attempt to abort the calling script.
-    """
-    try:
-        import setuptools
-        if setuptools.__version__ == '0.0.1':
-            print >>sys.stderr, (
-            "You have an obsolete version of setuptools installed.  Please\n"
-            "remove it from your system entirely before rerunning this script."
-            )
-            sys.exit(2)
-    except ImportError:
-        egg = download_setuptools(version, download_base, to_dir, download_delay)
-        sys.path.insert(0, egg)
-        import setuptools; setuptools.bootstrap_install_from = egg
-
-    import pkg_resources
-    try:
-        pkg_resources.require("setuptools>="+version)
-
-    except pkg_resources.VersionConflict, e:
-        # XXX could we install in a subprocess here?
-        print >>sys.stderr, (
-            "The required version of setuptools (>=%s) is not available, and\n"
-            "can't be installed while this script is running. Please install\n"
-            " a more recent version first.\n\n(Currently using %r)"
-        ) % (version, e.args[0])
-        sys.exit(2)
-
-def download_setuptools(
-    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
-    delay = 15
-):
-    """Download setuptools from a specified location and return its filename
-
-    `version` should be a valid setuptools version number that is available
-    as an egg for download under the `download_base` URL (which should end
-    with a '/'). `to_dir` is the directory where the egg will be downloaded.
-    `delay` is the number of seconds to pause before an actual download attempt.
-    """
-    import urllib2, shutil
-    egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
-    url = download_base + egg_name
-    saveto = os.path.join(to_dir, egg_name)
-    src = dst = None
-    if not os.path.exists(saveto):  # Avoid repeated downloads
-        try:
-            from distutils import log
-            if delay:
-                log.warn("""
----------------------------------------------------------------------------
-This script requires setuptools version %s to run (even to display
-help).  I will attempt to download it for you (from
-%s), but
-you may need to enable firewall access for this script first.
-I will start the download in %d seconds.
-
-(Note: if this machine does not have network access, please obtain the file
-
-   %s
-
-and place it in this directory before rerunning this script.)
----------------------------------------------------------------------------""",
-                    version, download_base, delay, url
-                ); from time import sleep; sleep(delay)
-            log.warn("Downloading %s", url)
-            src = urllib2.urlopen(url)
-            # Read/write all in one block, so we don't create a corrupt file
-            # if the download is interrupted.
-            data = _validate_md5(egg_name, src.read())
-            dst = open(saveto,"wb"); dst.write(data)
-        finally:
-            if src: src.close()
-            if dst: dst.close()
-    return os.path.realpath(saveto)
-
-def main(argv, version=DEFAULT_VERSION):
-    """Install or upgrade setuptools and EasyInstall"""
-
-    try:
-        import setuptools
-    except ImportError:
-        egg = None
-        try:
-            egg = download_setuptools(version, delay=0)
-            sys.path.insert(0,egg)
-            from setuptools.command.easy_install import main
-            return main(list(argv)+[egg])   # we're done here
-        finally:
-            if egg and os.path.exists(egg):
-                os.unlink(egg)
-    else:
-        if setuptools.__version__ == '0.0.1':
-            # tell the user to uninstall obsolete version
-            use_setuptools(version)
-
-    req = "setuptools>="+version
-    import pkg_resources
-    try:
-        pkg_resources.require(req)
-    except pkg_resources.VersionConflict:
-        try:
-            from setuptools.command.easy_install import main
-        except ImportError:
-            from easy_install import main
-        main(list(argv)+[download_setuptools(delay=0)])
-        sys.exit(0) # try to force an exit
-    else:
-        if argv:
-            from setuptools.command.easy_install import main
-            main(argv)
-        else:
-            print "Setuptools version",version,"or greater has been installed."
-            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
-
-
-
-def update_md5(filenames):
-    """Update our built-in md5 registry"""
-
-    import re
-    from md5 import md5
-
-    for name in filenames:
-        base = os.path.basename(name)
-        f = open(name,'rb')
-        md5_data[base] = md5(f.read()).hexdigest()
-        f.close()
-
-    data = ["    %r: %r,\n" % it for it in md5_data.items()]
-    data.sort()
-    repl = "".join(data)
-
-    import inspect
-    srcfile = inspect.getsourcefile(sys.modules[__name__])
-    f = open(srcfile, 'rb'); src = f.read(); f.close()
-
-    match = re.search("\nmd5_data = {\n([^}]+)}", src)
-    if not match:
-        print >>sys.stderr, "Internal error!"
-        sys.exit(2)
-
-    src = src[:match.start(1)] + repl + src[match.end(1):]
-    f = open(srcfile,'w')
-    f.write(src)
-    f.close()
-
-
-if __name__=='__main__':
-    if len(sys.argv)>2 and sys.argv[1]=='--md5update':
-        update_md5(sys.argv[2:])
-    else:
-        main(sys.argv[1:])
-
-
-
-
-

File wsgistate/file.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''File-based cache backend'''
+
+import os, time, urllib
+try:
+    import cPickle as pickle
+except ImportError:
+    import pickle
+from wsgistate.simple import SimpleCache
+from wsgistate.cache import WsgiMemoize
+from wsgistate.session import CookieSession, URLSession, SessionCache
+
+__all__ = ['FileCache', 'memoize', 'session', 'urlsession']
+
+
+def memoize(path, **kw):
+    '''Decorator for caching.
+
+    @param path Filesystem path
+    '''
+    def decorator(application):
+        _file_memo_cache = FileCache(path, **kw)
+        return WsgiMemoize(application, _file_memo_cache, **kw)
+    return decorator
+
+def session(path, **kw):
+    '''Decorator for sessions.
+
+    @param path Filesystem path
+    '''
+    def decorator(application):
+        _file_base_cache = FileCache(path, **kw)
+        _file_session_cache = SessionCache(_file_base_cache, **kw)
+        return CookieSession(application, _file_session_cache, **kw)
+    return decorator
+
+def urlsession(path, **kw):
+    '''Decorator for URL encoded sessions.
+
+    @param path Filesystem path
+    '''
+    def decorator(application):
+        _file_ubase_cache = FileCache(path, **kw)
+        _file_url_cache = SessionCache(_file_ubase_cache, **kw)
+        return URLSession(application, _file_url_cache, **kw)
+    return decorator
+
+
+class FileCache(SimpleCache):
+
+    '''File-based cache backend'''    
+    
+    def __init__(self, *a, **kw):
+        super(FileCache, self).__init__(*a, **kw)
+        # Create directory
+        try:
+            self._dir = a[0]
+        except IndexError:
+            raise IOError('file.FileCache requires a valid directory path.')
+        if not os.path.exists(self._dir): self._createdir()
+        # Remove unneeded methods and attributes
+        del self._cache
+
+    def __contains__(self, key):
+        '''Tell if a given key is in the cache.'''
+        return os.path.exists(self._key_to_file(key))
+
+    def get(self, key, default=None):
+        '''Fetch a given key from the cache.  If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        try:
+            exp, value = pickle.load(open(self._key_to_file(key), 'rb')) 
+            # Remove item if time has expired.
+            if exp < time.time():
+                self.delete(key)
+                return default
+            return value
+        except (IOError, OSError, EOFError, pickle.PickleError): pass
+        return default
+
+    def set(self, key, value):
+        '''Set a value in the cache.
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.        
+        '''        
+        if len(self.keys()) > self._max_entries: self._cull()
+        try:
+            fname = self._key_to_file(key)
+            pickle.dump((time.time() + self.timeout, value), open(fname, 'wb'), 2)
+        except (IOError, OSError): pass
+
+    def delete(self, key):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        try:
+            os.remove(self._key_to_file(key))
+        except (IOError, OSError): pass
+
+    def keys(self):
+        '''Returns a list of keys in the cache.'''
+        return os.listdir(self._dir)
+    
+    def _createdir(self):
+        '''Creates the cache directory.'''
+        try:
+            os.makedirs(self._dir)
+        except OSError:
+            raise EnvironmentError('Cache directory "%s" does not exist and ' \
+                'could not be created' % self._dir)
+
+    def _key_to_file(self, key):
+        '''Gives the filesystem path for a key.'''
+        return os.path.join(self._dir, urllib.quote_plus(key))

File wsgistate/memcached.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Memcached cache backend'''
+
+try:
+    import memcache
+except ImportError:
+    raise ImportError("Memcached cache backend requires the 'memcache' library")
+from wsgistate import BaseCache
+from wsgistate.cache import WsgiMemoize
+from wsgistate.session import CookieSession, URLSession, SessionCache
+
+__all__ = ['MemCached', 'memoize', 'session', 'urlsession']
+
+
+def memoize(path, **kw):
+    '''Decorator for caching.
+
+    @param path Client path
+    '''
+    def decorator(application):
+        _mc_memo_cache = MemCached(path, **kw)
+        return WsgiMemoize(application, _mc_memo_cache, **kw)
+    return decorator
+
+def session(path, **kw):
+    '''Decorator for sessions.
+
+    @param path Client path
+    '''
+    def decorator(application):
+        _mc_base_cache = MemCached(path, **kw)
+        _mc_session_cache = SessionCache(_mc_base_cache, **kw)
+        return CookieSession(application, _mc_session_cache, **kw)
+    return decorator
+
+def urlsession(path, **kw):
+    '''Decorator for URL encoded sessions.
+
+    @param path Client path
+    '''
+    def decorator(application):
+        _mc_ubase_cache = MemCached(path, **kw)
+        _mc_url_cache = SessionCache(_mc_ubase_cache, **kw)
+        return URLSession(application, _mc_url_cache, **kw)
+    return decorator
+
+
+class MemCached(BaseCache):
+
+    '''Memcached cache backend'''    
+    
+    def __init__(self, *a, **kw):
+        super(MemCached, self).__init__(*a, **kw)
+        self._cache = memcache.Client(a[0].split(';'))
+
+    def get(self, key, default=None):
+        '''Fetch a given key from the cache.  If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        val = self._cache.get(key)
+        if val is None: return default
+        return val
+
+    def set(self, key, value):
+        '''Set a value in the cache.
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.        
+        '''
+        self._cache.set(key, value, self.timeout)
+
+    def delete(self, key):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        self._cache.delete(key)
+
+    def get_many(self, keys):
+        '''Fetch a bunch of keys from the cache.
+
+        Returns a dict mapping each key in keys to its value.  If the given
+        key is missing, it will be missing from the response dict.
+
+        @param keys Keywords of items in cache.        
+        '''
+        return self._cache.get_multi(keys)
+
+    def _cull(self):
+        '''Stub.'''
+        pass

File wsgistate/memory.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2005 Allan Saddi <allan@saddi.com>
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Thread-safe in-memory cache backend.'''
+
+import copy, time
+try:
+    import threading
+except ImportError:
+    import dummy_threading as threading
+from wsgistate import synchronized
+from wsgistate.simple import SimpleCache
+from wsgistate.cache import WsgiMemoize
+from wsgistate.session import CookieSession, URLSession, SessionCache
+
+__all__ = ['MemoryCache', 'memoize', 'session', 'urlsession']
+
+def memoize(**kw):
+    '''Decorator for caching.'''
+    def decorator(application):
+        _mem_memo_cache = MemoryCache(**kw)
+        return WsgiMemoize(application, _mem_memo_cache, **kw)
+    return decorator
+
+def session(**kw):
+    '''Decorator for sessions.'''
+    def decorator(application):
+        _mem_base_cache = MemoryCache(**kw)
+        _mem_session_cache = SessionCache(_mem_base_cache, **kw)
+        return CookieSession(application, _mem_session_cache, **kw)
+    return decorator
+
+def urlsession(**kw):
+    '''Decorator for URL encoded sessions.'''
+    def decorator(application):
+        _mem_ubase_cache = MemoryCache(**kw)
+        _mem_url_cache = SessionCache(_mem_ubase_cache, **kw)
+        return URLSession(application, _mem_url_cache, **kw)
+    return decorator
+
+
+class MemoryCache(SimpleCache):
+
+    '''Thread-safe in-memory cache backend.'''    
+
+    def __init__(self, *a, **kw):
+        super(MemoryCache, self).__init__(*a, **kw)
+        self._lock = threading.Condition()
+        
+    @synchronized        
+    def get(self, key, default=None):
+        '''Fetch a given key from the cache. If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        return copy.deepcopy(super(MemoryCache, self).get(key))
+
+    @synchronized
+    def set(self, key, value):
+        '''Set a value in the cache.  
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.        
+        '''
+        super(MemoryCache, self).set(key, value)
+
+    @synchronized
+    def delete(self, key):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        super(MemoryCache, self).delete(key)

File wsgistate/session.py

+# Copyright (c) 2005 Allan Saddi <allan@saddi.com>
+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2006 L. C. Rees
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in the
+#    documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+import os
+import string
+import weakref
+import atexit
+import cgi
+import urllib
+import sha
+import random
+import sys
+from Cookie import SimpleCookie
+from urllib import quote
+try:
+    import threading
+except ImportError:
+    import dummy_threading as threading
+from wsgistate import synchronized
+
+__all__ = ['SessionCache', 'SessionManager', 'CookieSession', 'URLSession',
+     'session', 'urlsession']
+
+def _shutdown(ref):
+    cache = ref()
+    if cache is not None: cache.shutdown()
+    
+def session(cache, **kw):
+    '''Decorator for sessions.'''
+    def decorator(application):
+        return CookieSession(application, cache, **kw)
+    return decorator
+
+def urlsession(cache, **kw):
+    '''Decorator for URL encoded sessions.'''
+    def decorator(application):
+        return URLSession(application, cache, **kw)
+    return decorator
+
+
+class SessionCache(object):
+    
+    '''Base class for session cache. You first acquire a session by
+    calling create() or checkout(). After using the session, you must call
+    checkin(). You must not keep references to sessions outside of a check
+    in/check out block. Always obtain a fresh reference.
+    '''
+    # Would be nice if len(idchars) were some power of 2.
+    idchars = '-_'.join([string.digits, string.ascii_letters])
+    length = 64
+
+    def __init__(self, cache, **kw):
+        self._lock = threading.Condition()
+        self.checkedout, self._closed, self.cache = dict(), False, cache
+        # Sets if session id is random on every access or not
+        self._random = kw.get('random', False)
+        self._secret = ''.join(self.idchars[ord(c) % len(self.idchars)]
+            for c in os.urandom(self.length))
+        # Ensure shutdown is called.
+        atexit.register(_shutdown, weakref.ref(self))
+
+    def __del__(self):
+        self.shutdown()
+
+    # Public interface.
+
+    @synchronized
+    def create(self):
+        '''Create a new session with a unique identifier.
+        
+        The newly-created session should eventually be released by
+        a call to checkin().            
+        '''
+        sid, sess = self.newid(), dict()
+        self.cache.set(sid, sess)            
+        self.checkedout[sid] = sess
+        return sid, sess
+
+    @synchronized
+    def checkout(self, sid):
+        '''Checks out a session for use. Returns the session if it exists,
+        otherwise returns None. If this call succeeds, the session
+        will be touch()'ed and locked from use by other processes.
+        Therefore, it should eventually be released by a call to
+        checkin().
+
+        @param sid Session id        
+        '''
+        # If we know it's already checked out, block.
+        while sid in self.checkedout: self._lock.wait()
+        sess = self.cache.get(sid)
+        if sess is not None:
+            # Randomize session id if set and remove old session id
+            if self._random:
+                self.cache.delete(sid)
+                sid = self.newid()
+            # Put in checkout
+            self.checkedout[sid] = sess
+            return sid, sess
+        return None, None
+
+    @synchronized
+    def checkin(self, sid, sess):
+        '''Returns the session for use by other threads/processes.
+
+        @param sid Session id
+        @param session Session dictionary
+        '''
+        del self.checkedout[sid]
+        self.cache.set(sid, sess)
+        self._lock.notify()
+
+    @synchronized
+    def shutdown(self):
+        '''Clean up outstanding sessions.'''        
+        if not self._closed:
+            # Save or delete any sessions that are still out there.
+            for sid, sess in self.checkedout.iteritems():
+                self.cache.set(sid, sess)
+            self.checkedout.clear()
+            self.cache._cull()                
+            self._closed = True
+
+    # Utilities
+
+    def newid(self):
+        'Returns session key that is not being used.'
+        sid = None
+        for num in xrange(10000):
+            sid = sha.new(str(random.randint(0, sys.maxint - 1)) +
+              str(random.randint(0, sys.maxint - 1)) + self._secret).hexdigest()
+            if sid not in self.cache: break
+        return sid
+            
+
+class SessionManager(object):
+
+    '''Session Manager.'''  
+
+    def __init__(self, cache, environ, **kw):
+        self._cache = cache
+        self._fieldname = kw.get('fieldname', '_SID_')
+        self._path = kw.get('path', '/')
+        self.session = self._sid = self._csid = None
+        self.expired = self.current = self.new = self.inurl = False
+        self._get(environ)
+
+    def _fromcookie(self, environ):
+        '''Attempt to load the associated session using the identifier from
+        the cookie.
+        '''
+        cookie = SimpleCookie(environ.get('HTTP_COOKIE'))
+        morsel = cookie.get(self._fieldname, None)
+        if morsel is not None:
+            self._sid, self.session = self._cache.checkout(morsel.value)
+            self._csid = morsel.value
+            if self._csid != self._sid: self.new = True
+
+    def _fromquery(self, environ):
+        '''Attempt to load the associated session using the identifier from
+        the query string.
+        '''
+        self._qdict = dict(cgi.parse_qsl(environ.get('QUERY_STRING', '')))
+        value = self._qdict.get(self._fieldname)
+        if value is not None:
+            self._sid, self.session = self._cache.checkout(value)
+            if self._sid is not None:
+                self._csid, self.inurl = value, True
+                if self._csid != self._sid: self.current = self.new = True
+        
+    def _get(self, environ):
+        '''Attempt to associate with an existing Session.'''
+        # Try cookie first.
+        self._fromcookie(environ)
+        # Next, try query string.
+        if self.session is None: self._fromquery(environ)
+        if self.session is None:
+            self._sid, self.session = self._cache.create()
+            self.new = True
+    
+    def close(self):
+        '''Checks session back into session cache.'''
+        # Check the session back in and get rid of our reference.
+        self._cache.checkin(self._sid, self.session)
+        self.session = None
+   
+    def setcookie(self, headers):
+        '''Sets a cookie header if needed.''' 
+        cookie, name = SimpleCookie(), self._fieldname
+        cookie[name], cookie[name]['path'] = self._sid, self._path
+        headers.append(('Set-Cookie', cookie[name].OutputString()))
+
+    def seturl(self, environ):
+        '''Encodes session ID in URL, if necessary.'''
+        path = ''.join([quote(environ.get('SCRIPT_NAME', '')),
+            quote(environ.get('PATH_INFO', ''))])
+        # Get query
+        if self._qdict:
+            self._qdict[self._fieldname] = self._sid
+        else:
+            self._qdict = {self._fieldname:self._sid}
+        return '?'.join([path, urllib.urlencode(self._qdict)])
+        
+class _Session(object):
+
+    '''WSGI middleware that adds a session service.'''
+
+    def __init__(self, application, cache, **kw):
+        self.application, self.cache, self.kw = application, cache, kw
+        # environ key
+        self.key = kw.get('key', 'com.saddi.service.session')
+
+    def __call__(self, environ, start_response):
+        # New session manager instance each time
+        sess = SessionManager(self.cache, environ, **self.kw)
+        environ[self.key] = sess
+        try:
+            # Return intial response if new or session id is random
+            if sess.new: return self._initial(environ, start_response)                
+            return self.application(environ, start_response)
+        # Always close session
+        finally:            
+            sess.close()
+            
+
+class CookieSession(_Session):            
+
+    '''WSGI middleware that adds a session service in a cookie.'''
+
+    def _initial(self, environ, start_response):
+        '''Initial response to a cookie session.'''
+        def session_response(status, headers, exc_info=None):
+            environ[self.key].setcookie(headers)
+            return start_response(status, headers, exc_info)
+        return self.application(environ, session_response)
+
+
+class URLSession(_Session):
+    
+    '''WSGI middleware that adds a session service in a URL query string.'''
+
+    def _initial(self, environ, start_response):
+        '''Initial response to a query encoded session.'''
+        url = environ[self.key].seturl(environ)
+        # Redirect to URL with session in query component
+        start_response('302 Found', [('location', url)])
+        return ['The browser is being redirected to %s' % url]   

File wsgistate/setup.py

-# Copyright (c) 2006 L. C. Rees.  All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# 1.  Redistributions of source code must retain the above copyright notice,
-# this list of conditions and the following disclaimer.
-# 2.  Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# 3.  Neither the name of the Portable Site Information Project nor the names
-# of its contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-'''setup - setuptools based setup for wsgistate.'''
-
-import ez_setup
-ez_setup.use_setuptools()
-
-try:
-    from setuptools import setup
-except:
-    from distutils.core import setup
-
-setup(name='wsgistate',
-      version='0.4.1',
-      description='''WSGI session and caching middleware.''',
-      long_description='''Session (flup-compatible), caching, memoizing, and HTTP cache control
-middleware for WSGI. Supports memory, filesystem, database, and memcached based backends.
-
-# Simple memoization example:
-
-from wsgistate.memory import memoize
-
-@memoize()
-def app(environ, start_response):
-    start_response('200 OK', [('Content-Type', 'text/plain')])
-    return ['Hello World!']
-
-if __name__ == '__main__':
-    from wsgiref.simple_server import make_server
-    http = make_server('', 8080, app)
-    http.serve_forever()
-
-# Simple session example:
-
-from wsgistate.memory import session
-
-@session()
-def app(environ, start_response):
-    session = environ['com.saddi.service.session'].session
-    count = session.get('count', 0) + 1
-    session['count'] = count
-    start_response('200 OK', [('Content-Type', 'text/plain')])
-    return ['You have been here %d times!\n' % count]
-
-if __name__ == '__main__':
-    from wsgiref.simple_server import make_server
-    http = make_server('', 8080, app)
-    http.serve_forever()''',
-      author='L. C. Rees',
-      author_email='lcrees@gmail.com',
-      license='BSD',
-      packages = ['wsgistate'],
-      test_suite='wsgistate.tests',
-      zip_safe = True,
-      keywords='WSGI session caching persistence memoizing HTTP Web',
-      classifiers=['Development Status :: 4 - Beta',
-                    'Environment :: Web Environment',
-                    'License :: OSI Approved :: BSD License',
-                    'Natural Language :: English',
-                    'Operating System :: OS Independent',
-                    'Programming Language :: Python',
-                    'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware'],
-      install_requires = ['SQLAlchemy'],)

File wsgistate/simple.py

+# Copyright (c) 2005, the Lawrence Journal-World
+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of Django nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Single-process in-memory cache backend.'''
+
+import time
+import random
+from wsgistate import BaseCache
+from wsgistate.cache import WsgiMemoize
+from wsgistate.session import CookieSession, URLSession, SessionCache
+
+__all__ = ['SimpleCache', 'memoize', 'session', 'urlsession']
+
+def memoize(**kw):
+    '''Decorator for caching.'''
+    def decorator(application):
+        _simple_memo_cache = SimpleCache(**kw)
+        return WsgiMemoize(application, _simple_memo_cache, **kw)
+    return decorator
+
+def session(**kw):
+    '''Decorator for sessions.'''
+    def decorator(application):
+        _simple_base_cache = SimpleCache(**kw)
+        _simple_session_cache = SessionCache(_simple_base_cache, **kw)
+        return CookieSession(application, _simple_session_cache, **kw)
+    return decorator
+
+def urlsession(**kw):
+    '''Decorator for URL encoded sessions.'''
+    def decorator(application):
+        _simple_ubase_cache = SimpleCache(**kw)
+        _simple_url_cache = SessionCache(_simple_ubase_cache, **kw)
+        return URLSession(application, _simple_url_cache, **kw)
+    return decorator
+
+
+class SimpleCache(BaseCache):
+
+    '''Single-process in-memory cache backend.'''    
+    
+    def __init__(self, *a, **kw):
+        super(SimpleCache, self).__init__(*a, **kw)
+        # Get random seed
+        random.seed()        
+        self._cache = dict()
+        # Set max entries
+        max_entries = kw.get('max_entries', 300)
+        try:
+            self._max_entries = int(max_entries)
+        except (ValueError, TypeError):
+            self._max_entries = 300
+        # Set maximum number of items to cull if over max
+        self._maxcull = kw.get('maxcull', 10)
+
+    def get(self, key, default=None):
+        '''Fetch a given key from the cache.  If the key does not exist, return
+        default, which itself defaults to None.
+
+        @param key Keyword of item in cache.
+        @param default Default value (default: None)
+        '''
+        values = self._cache.get(key)
+        if values is None: return default
+        # Delete if item timed out and return default.
+        if values[0] < time.time():
+            self.delete(key)
+            return default
+        return values[1] 
+
+    def set(self, key, value):
+        '''Set a value in the cache.
+
+        @param key Keyword of item in cache.
+        @param value Value to be inserted in cache.        
+        '''
+        # Cull timed out values if over max # of entries
+        if len(self._cache) >= self._max_entries: self._cull()
+        # Set value and timeout in cache
+        self._cache[key] = (time.time() + self.timeout, value)
+
+    def delete(self, key):
+        '''Delete a key from the cache, failing silently.
+
+        @param key Keyword of item in cache.
+        '''
+        try:
+            del self._cache[key]
+        except KeyError: pass
+
+    def keys(self):
+        '''Returns a list of keys in the cache.'''
+        return self._cache.keys()
+
+    def _cull(self):
+        '''Remove items in cache to make room.'''        
+        num, maxcull = 0, self._maxcull
+        # Cull number of items allowed (set by self._maxcull)
+        for key in self.keys():
+            # Remove only maximum # of items allowed by maxcull
+            if num <= maxcull:
+                # Remove items if expired
+                if self.get(key) is None: num += 1
+            else: break
+        # Remove any additional items up to max # of items allowed by maxcull
+        while len(self.keys()) >= self._max_entries and num <= maxcull:
+            # Cull remainder of allowed quota at random
+            self.delete(random.choice(self.keys()))
+            num += 1

File wsgistate/tests/__init__.py

Empty file added.

File wsgistate/tests/test_wsgistate.py

+# Copyright (c) 2006 L. C. Rees
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#    
+#    2. Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#    3. Neither the name of psilib nor the names of its contributors may be used
+#       to endorse or promote products derived from this software without
+#       specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Unit tests for wsgistate.'''
+
+import unittest
+import StringIO
+import copy
+import os
+import time
+from wsgistate import *
+import urlparse
+