DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Fake Memcache Server

09.22.2008
| 3552 views |
  • submit to reddit
        A small fake memcache, mimics the 'import memcache' module Useful for testing without a real memcache server to connect to, nowhere near complete (missing methods like flush_all()) for example, although if someone was to take the time...


class Memcache(object):
    """
    usage:
    >>> mc = Memcache()
    >>> mc.set('joe', 4)
    >>> mc.get('joe')
    4
    """

    cache = {}

    def set(self, key, value):
        assert(isinstance(key, basestring))
        self.cache[key] = value

    def set_multi(self, keys_values):
        for key in keys_values:
            assert(isinstance(key, basestring))
        self.cache.update(keys_values)

    def get(self, key):
        assert(isinstance(key, basestring))
        return self.cache.get(key, None)

    def get_multi(self, key_list, key_prefix=''):
        for key in key_list:
            assert(isinstance(key, basestring))
        result = {}
        for key in key_list:
            ckey = key_prefix+key
            if ckey in self.cache:
                result[key] = self.cache[ckey]
        return result