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

  • 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):
    >>> mc = Memcache()
    >>> mc.set('joe', 4)
    >>> mc.get('joe')

    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))

    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