Skip to content

Memcached in 2 Minutes

So you need to use memcached with Python? Below is a brief intro.

First install everything you need. I run Ubuntu so python-memcached memcached packages were required. python-memcached is available from and the memcached site is available here

Start the memcached server if its not already running:

/usr/bin/memcached -m 64 -p 11211 -u nobody -l

The above gets you a 64Mb server, more than enough to play on.

Next some python below is from the interpreter:

>>> import memcache
>>> memc = memcache.Client([''])
>>> class test():
>>>    def __init__(self):
>>>        self.message = "Hello, world"
>>> t = test()
>>> memc.set('testname', t, 120)
>>> got = memc.get('testname')
>>> got.message
'Hello, world'

The above instantiates an object and then saves it memcached with set() and then we get it back using get(). In the set call we specify the number 120, this is the number of seconds the object should be held in the cache. The usage is pretty simple: try and fetch from memcached if it fails fetch from your datasource and then save that document ready for next time.