Permalink
Browse files

Add namespace prefixes to cache instances to avoid collisions, as a m…

…emcached server will be shared by multiple cache instances in urldammit
  • Loading branch information...
1 parent 900d219 commit 57afa8691684ec28bce0395d2d5b1f500c9d0485 @harryf committed Jun 26, 2008
Showing with 35 additions and 12 deletions.
  1. +20 −3 dammit/cachemanager.py
  2. +1 −1 dammit/db_cache.py
  3. +12 −6 dammit/mcwrapper.py
  4. +2 −2 urldammit.py
View
23 dammit/cachemanager.py
@@ -15,11 +15,28 @@ def register_cache_constructor(func):
global cache_constructor
cache_constructor = func
-def new_instance():
+def new_instance(namespace):
"""
- Create a new instance of the current cache class
+ Create a new instance of the current cache class
+
+ For a shared cache (e.g. memcached), we need to
+ pass some identifier to prevent keys colliding
+ hence the namespace param (e.g. use as key prefix
+ for memcached impl)
+ """
+ return cache_constructor(namespace)
+
+def namespacer(func):
+ """
+ Decorator for injecting a namespace prefix into
+ the key argument, obtained from self.namespace
"""
- return cache_constructor()
+ def namespace_wrapper(self, key, *args, **kwargs):
+ return func(
+ self,
+ key = "%s_%s" % ( self.namespace, key, *args, **kwargs )
+ )
+ return namespace_wrapper
def _test():
"""
View
2 dammit/db_cache.py
@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
import cachemanager
-cache = cachemanager.new_instance()
+cache = cachemanager.new_instance('db')
def load(method):
"""
View
18 dammit/mcwrapper.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+from cachemanager import namespacer
+
class MemcachedWrapper(object):
"""
Wrapper around an memcached.Client object to implement
@@ -21,28 +23,32 @@ class MemcachedWrapper(object):
>>> 'foo' in mcw
False
"""
- def __init__(self, mc):
+ def __init__(self, mc, namespace):
self.mc = mc
def __len__(self):
raise Exception("Not implemented")
-
+
+ @namespacer
def __contains__(self, key):
return self.mc.get(key) != None
-
+
+ @namespacer
def __setitem__(self, key, val):
self.mc.set(key, val)
-
+
+ @namespacer
def __getitem__(self, key):
val = self.mc.get(key)
if val == None:
raise KeyError(key)
return val
-
+
+ @namespacer
def __delitem__(self, key):
if self.mc.delete(key) == 0:
raise KeyError(key)
-
+
def __repr__(self):
return "MemcachedWrapper"
View
4 urldammit.py
@@ -22,11 +22,11 @@
manager = URIManager(config.get_db())
# cache URIs we know about
-known = cachemanager.new_instance()
+known = cachemanager.new_instance('known')
# cache queries we know nothing about otherwise
# we have to ask couch each time
-unknown = cachemanager.new_instance()
+unknown = cachemanager.new_instance('unknown')
class urldammit(object):
"""

0 comments on commit 57afa86

Please sign in to comment.