Total Pageviews

Google Ads

Tuesday, May 28, 2013

Install memcache python with python-memcached and pylibmc


Cache server become more important day by day. Almost project need a cache server to increase speed and performance. Memcached is a cache service provide RAM Cache for any program (like web, game server, ...). In this article, I will introduce about how to use memcached with Python.

For using python memcache in your project, you can use python-memcached or using pylibmc (python library for memcache). of course, it's only a interface for connecting and working with memcache server so as first we need to install memcached server.

Install Memcache server

for ubuntu - Xubuntu - ...

 sudo apt-get install memcached  

for CentOS - Fedora - Redhat ...

 yum install memcached  

after installing complete you can check is it running with:

 $ telnet localhost 11211  
 Trying 127.0.0.1...  
 Connected to localhost.  
 Escape character is '^]'.  
 get foo  
 VALUE foo 0 2  
 hi  
 END  
 stats  
 STAT pid 8861  
 (etc)  

python-memcached library

After it work. We need to install python-memcached (you can forget this step if you install pylibmc)
for ubuntu: (Notice : let sure you install pip before. if you haven't, try "su apt-get install python-pip"

 pip install python-memcached  


for CentOS: (Notice : we will use pip-python to install python-memcached so let sure pip-python install in your system [ yum install python-pip ]

 pip-python install python-memcached  

Try some exsample with python-memcached

 python  
 import memcache  
 mc = memcache.Client(['127.0.0.1:11211'], debug=0)  
 mc.set("some_key", "Some value")  
 mc.get("some_key")  
 mc.set("another_key", 3)  
 mc.delete("another_key")

pylibmc library

pylibmc is a lib base on C. I hear some people say It's faster than python-memcached lib

Ubuntu - debian
 sudo apt-get install -y libmemcached-dev zlib1g-dev libssl-dev python-dev build-essential  
 pip install pylibmc  

CentOS - Fedora - Redhat

  yum install libmemcached 
  pip-python install pylibmc 

try some sample:

 python
 >>> import pylibmc  
 >>> mc = pylibmc.Client(["127.0.0.1"], binary=True,  
 ...           behaviors={"tcp_nodelay": True,  
 ...                "ketama": True})  
 >>> mc["some_key"] = "Some value"  
 >>> mc["some_key"]  
 'Some value'  
 >>> del mc["some_key"]  
 >>> "some_key" in mc  
 False  

for more document. please visit pylibmc Page

Performance comparison  of pylibmc library and python-memcached library in here

No comments:

Post a Comment