Commits

Lynn Rees committed ebb2719

- restructure repository after import

  • Participants
  • Parent commits d9f41b8
  • Branches wsgistate

Comments (0)

Files changed (73)

branches/0.2/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.6c3"
+DEFAULT_URL     = "http://cheeseshop.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',
+}
+
+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:])
+
+
+
+
+

branches/0.2/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.3',
+      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 MemoryCache
+from wsgistate.cache import memoize
+
+cache = MemoryCache()
+
+@memoize(cache)
+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 MemoryCache
+from wsgistate.session import session, SessionCache
+
+cache = MemoryCache()
+
+@session(SessionCache(cache))
+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 :: 3 - Alpha',
+                    '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'],)

branches/0.2/trunk/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.6c3"
-DEFAULT_URL     = "http://cheeseshop.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',
-}
-
-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:])
-
-
-
-
-

branches/0.2/trunk/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.3',
-      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 MemoryCache
-from wsgistate.cache import memoize
-
-cache = MemoryCache()
-
-@memoize(cache)
-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 MemoryCache
-from wsgistate.session import session, SessionCache
-
-cache = MemoryCache()
-
-@session(SessionCache(cache))
-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 :: 3 - Alpha',
-                    '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'],)

branches/0.2/trunk/wsgistate/__init__.py

-__all__ = ['base', 'db', 'file', 'memory', 'memcached', 'session', 'simple', 'cache']

branches/0.2/trunk/wsgistate/base.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']
-
-
-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.  For certain backends
-        (memcached, pgsql) this can be *much* faster when fetching multiple values.
-
-        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

branches/0.2/trunk/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 copy import copy
-
-__all__ = ['WsgiMemoize', 'CacheHeader', 'memoize', 'public', 'private',
-    'nocache', 'nostore', 'notransform', 'revalidate', 'proxyrevalidate',
-    'maxage', 'smaxage', 'vary', 'modified']
-
-def expiredate(seconds, value):
-    '''Expire date headers for cache control.
-
-    @param seconds Seconds
-    @
-    '''
-    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):
-        # 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']
-        # Verify requested response is cacheable
-        if environ['REQUEST_METHOD'] in self._allowed:
-            # 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)
-            # Get response from WSGI stack
-            data = self.application(environ, cache_response)
-            # Fetch cached start_response data
-            info = self._cache[key]
-            # Add response
-            info['data'] = data
-            self._cache[key] = info
-            # Return data as response to intial request
-            return data
-        return self.application(environ, start_response)
-
-    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 = copy(environ['wsgi.input']).read()
-                if win != '': key.append(win)
-        return ''.join(key)

branches/0.2/trunk/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.base import BaseCache
-
-__all__ = ['DbCache']
-
-
-class DbCache(BaseCache):     
-
-    '''Database cache backend.'''
-
-    def __init__(self, *a, **kw):
-        super(DbCache, self).__init__(self, *a, **kw)
-        # Bind metadata
-        self._metadata = BoundMetaData(a[0])
-        # Make cache
-        self._cache = Table('cache', self._metadata,
-            Column('id', Integer, primary_key=True, nullable=False, unique=True),
-            Column('cache_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()
-        max_entries = kw.get('max_entries', 300)
-        try:
-            self._max_entries = int(max_entries)
-        except (ValueError, TypeError):
-            self._max_entries = 300
-
-    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)
-        '''
-        row = self._cache.select().execute(cache_key=key).fetchone()
-        if row is None: return default
-        if row.expires < datetime.now().replace(microsecond=0):
-            self.delete(key)
-            return default
-        return row.value
-
-    def set(self, key, val):
-        '''Set a value in the cache.
-
-        @param key Keyword of item in cache.
-        @param value Value to be inserted in cache.        
-        '''
-        
-        timeout = self.timeout
-        # Get count
-        num = self._cache.count().execute().fetchone()[0]
-        if num > self._max_entries: self._cull()
-        # Get expiration time
-        exp = datetime.fromtimestamp(time.time() + timeout).replace(microsecond=0)        
-        try:
-            # Update database if key already present
-            if key in self:
-                self._cache.update(self._cache.c.cache_key==key).execute(value=val, expires=exp)
-            # Insert new key if key not present
-            else:            
-                self._cache.insert().execute(cache_key=key, value=val, expires=exp)
-        # To be threadsafe, updates/inserts are allowed to fail silently
-        except: pass
-       
-    def delete(self, key):
-        '''Delete a key from the cache, failing silently.
-
-        @param key Keyword of item in cache.
-        '''
-        self._cache.delete().execute(cache_key=key) 
-
-    def _cull(self):
-        '''Remove items in cache that have timed out.'''
-        now = datetime.now().replace(microsecond=0)
-        self._cache.delete(self._cache.c.expires < now).execute()

branches/0.2/trunk/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
-
-__all__ = ['FileCache']
-
-
-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
-        del self._expire_info
-
-    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)
-        '''
-        fname = self._key_to_file(key)
-        try:
-            f = open(fname, 'rb')
-            exp, now = pickle.load(f), time.time()
-            # Remove item if time has expired.
-            if exp < now:
-                f.close()
-                os.remove(fname)
-            else:
-                return pickle.load(f)
-        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.        
-        '''
-        fname = self._key_to_file(key)
-        try:
-            filelist = os.listdir(self._dir)
-        except (IOError, OSError):
-            self._createdir()
-            filelist = list()
-        if len(filelist) > self._max_entries: self._cull()
-        try:
-            f = open(fname, 'wb')
-            now = time.time()
-            pickle.dump(now + self.timeout, f, 2)
-            pickle.dump(value, f, 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 _cull(self):
-        '''Remove items in cache that have timed out.'''
-        try:
-            filelist = os.listdir(self._dir)
-        except (IOError, OSError):
-            self._createdir()
-            filelist = list()
-        for fname in filelist:
-            # Remove expired items from cache.
-            try:
-                f = open(fname, 'rb')
-                exp = pickle.load(f)
-                now = time.time()
-                if exp < now:
-                    f.close()
-                    try:
-                        os.remove(os.path.join(self._dir, fname))
-                    except (IOError, OSError): pass
-            except (IOError, OSError, EOFError, pickle.PickleError): pass            
-
-    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))

branches/0.2/trunk/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.base import BaseCache
-
-__all__ = ['MemCached']
-
-
-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
-        else:
-            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

branches/0.2/trunk/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.simple import SimpleCache
-
-__all__ = ['MemoryCache']
-
-class MemoryCache(SimpleCache):
-
-    '''Thread-safe in-memory cache backend.'''    
-
-    def __init__(self, *a, **kw):
-        super(MemoryCache, self).__init__(*a, **kw)
-        self._lock = threading.Condition()
-        
-    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)
-        '''
-        self._lock.acquire()
-        try:
-            now, exp = time.time(), self._expire_info.get(key)
-            if exp is None:
-                return default
-            # Return default value if item expired
-            elif exp < now:
-                self.delete(key)
-                return default
-            else:
-                return copy.deepcopy(self._cache[key])
-        finally:
-            self._lock.release()
-
-    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._lock.acquire()
-        try:
-            super(MemoryCache, self).set(key, value)
-        finally:
-            self._lock.release()
-
-    def delete(self, key):
-        '''Delete a key from the cache, failing silently.
-
-        @param key Keyword of item in cache.
-        '''
-        self._lock.acquire()
-        try:
-            super(MemoryCache, self).delete(key)
-        finally:
-            self._lock.release()

branches/0.2/trunk/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
-
-__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.
-
-    def create(self):
-        '''Create a new session with a unique identifier.
-        
-        The newly-created session should eventually be released by
-        a call to checkin().            
-        '''
-        self.lock.acquire()
-        try:
-            sid, sess = self.newid(), dict()
-            self.cache.set(sid, sess)            
-            self.checkedout[sid] = sess
-            return sid, sess
-        finally:
-            self.lock.release()
-
-    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        
-        '''
-        self.lock.acquire()
-        try:
-            # 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
-        finally:
-            self.lock.release()
-
-    def checkin(self, sid, sess):
-        '''Returns the session for use by other threads/processes.
-
-        @param sid Session id
-        @param session Session dictionary
-        '''
-        self.lock.acquire()
-        try:
-            del self.checkedout[sid]
-            self.cache.set(sid, sess)
-            self.lock.notify()
-        finally:            
-            self.lock.release()
-
-    def shutdown(self):
-        '''Clean up outstanding sessions.'''
-        self.lock.acquire()
-        try:
-            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
-        finally:
-            self.lock.release()
-
-    # 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]   

branches/0.2/trunk/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
-from wsgistate.base import BaseCache
-
-__all__ = ['SimpleCache']
-
-
-class SimpleCache(BaseCache):
-
-    '''Single-process in-memory cache backend.'''    
-    
-    def __init__(self, *a, **kw):
-        super(SimpleCache, self).__init__(*a, **kw)
-        self._cache, self._expire_info = dict(), dict()
-        max_entries = kw.get('max_entries', 300)
-        try:
-            self._max_entries = int(max_entries)
-        except (ValueError, TypeError):
-            self._max_entries = 300
-
-    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)
-        '''
-        now, exp = time.time(), self._expire_info.get(key)
-        if exp is None:
-            return default
-        # Delete if item timed out and return default.
-        elif exp < now:
-            self.delete(key)
-            return default
-        else:
-            return self._cache[key]
-
-    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()
-        self._cache[key] = value
-        # Set timeout
-        self._expire_info[key] = time.time() + self.timeout
-
-    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
-        try:
-            del self._expire_info[key]
-        except KeyError: pass
-
-    def _cull(self):
-        '''Remove items in cache that have timed out.'''
-        now = time.time()
-        for key, exp in self._expire_info.iteritems():
-            if exp < now: self.delete(key)

branches/0.2/trunk/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
-
-
-class TestWsgiState(unittest.TestCase):
-    
-    '''Test cases for wsgistate.'''
-        
-    def dummy_sr(self, status, headers, exc_info=None):
-        return headers
-    
-    def my_app(self, environ, start_response):
-        session = environ['com.saddi.service.session'].session
-        count = session.get('count', 0) + 1
-        session['count'] = count
-        environ['count'] = count
-        headers = start_response('200 OK', [])
-        if headers: environ['cookie'] = headers[0][1]
-        return environ
-
-    def my_app2(self, environ, start_response):
-        session = environ['com.saddi.service.session'].session
-        count = session.get('count', 0) + 1
-        session['count'] = count
-        environ['count'] = count
-        headers = start_response('200 OK', [])
-        return environ
-
-    def my_app3(self, environ, start_response):
-        start_response('200 OK', [])
-        return ['passed']
-
-    def test_sc_set_getitem(self):
-        '''Tests __setitem__ and __setitem__ on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache['test'] = 'test'
-        self.assertEqual(cache['test'], 'test')
-
-    def test_sc_set_get(self):
-        '''Tests set and get on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache.set('test', 'test')
-        self.assertEqual(cache.get('test'), 'test')
-
-    def test_sc_delitem(self):
-        '''Tests __delitem__ on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache['test'] = 'test'
-        del cache['test']
-        self.assertEqual(cache.get('test'), None)
-
-    def test_sc_set_get(self):
-        '''Tests delete on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache.set('test', 'test')
-        cache.delete('test')
-        self.assertEqual(cache.get('test'), None)
-
-    def test_set_getmany(self):
-        '''Tests delete on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache.set('test', 'test')
-        cache.set('test2', 'test2')
-        self.assertEqual(sorted(cache.get_many(('test', 'test2')).values()), ['test', 'test2'])
-
-    def test_sc_in_true(self):
-        '''Tests in (true) on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache.set('test', 'test')
-        self.assertEqual('test' in cache, True)
-
-    def test_sc_in_false(self):
-        '''Tests in (false) on SimpleCache.'''
-        cache = simple.SimpleCache()
-        cache.set('test2', 'test')
-        self.assertEqual('test' in cache, False)