Python 中使用 Python-memcache (memcached)的好例子?

我正在使用 Python 和 web.py 框架编写一个 web 应用程序,我需要在整个过程中使用 memcached。

我一直在互联网上搜索,试图找到一些好的文件上的 Python-memcached模块,但我能找到的是 这个例子在 MySQL 网站上,其方法的文件是不是很大。

108480 次浏览

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)


Overview
========


See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.


Usage summary
=============


This should give you a feel for how this module operates::


import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)


mc.set("some_key", "Some value")
value = mc.get("some_key")


mc.set("another_key", 3)
mc.delete("another_key")


mc.set("key", "1")   # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")


The standard way to use memcache with a database is like this::


key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)


# we now have obj, and future passes through this code
# will use the object from the cache.


Detailed Documentation
======================


More detailed documentation is available in the L{Client} class.
"""

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)


------------------------------------------
NAME
memcache - client module for memcached (memory cache daemon)


FILE
/usr/lib/python2.7/dist-packages/memcache.py


MODULE DOCS
http://docs.python.org/library/memcache


DESCRIPTION
Overview
========


See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.


Usage summary
=============
...
------------------------------------------