Yak Shaving

just me

A Quick memcache demo for Python

without comments

So you need to use memcache with Python? Below is a brief intro I figured out in about 20 mins.

First install everything you need. I run Ubuntu so python-memcached memcached packages were required.

Next start the memcached server if its not already running:

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

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

Next some python below is from the interpreter as I was in a hurry:

import memcache
memc = memcache.Client(['127.0.0.1:11211'])
class test():
    def __init__(self):
        self.m = "Hello, world"

t = test()
memc.set('cheese', t, 120)
True
r = memc.get('cheese')
r.m
'Hello, world'

The above instantiates an object and then saves it memcached with set() and then we get it back using get(). Dead simple. The usage is pretty, try and fetch from memcached if if fails fetch from your datasource and then save that document ready for next time.

memc.set(‘cheese’, t, 120) cheese is the reference, t is the object to store and 120 is the time to live. After 120 seconds the object is cleared from the cache.

Written by channam

June 21st, 2009 at 10:47 pm

Posted in Uncategorized

Leave a Reply