Python中使用python-memcache(memcached)的好例子有哪些?

95 投票
3 回答
111494 浏览
提问于 2025-04-15 11:37

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

我在网上搜索,想找一些关于python-memcached模块的好文档,但我找到的只有MySQL网站上的这个例子,而且关于它的方法的文档也不是很好。

3 个回答

8

一个简单的经验法则是:使用Python自带的帮助系统。下面是一个例子...

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
    =============
...
------------------------------------------
43

我建议你使用 pylibmc

它可以直接替代 python-memcache,而且速度更快(因为它是用 C 语言写的)。你可以在 这里 找到很方便的文档。

至于问题,因为 pylibmc 只是一个直接替代品,你仍然可以参考 pylibmc 的文档来进行 python-memcache 的编程。

147

这其实很简单。你可以用“键”来写入值,并设置过期时间。然后你可以通过“键”来获取这些值。你也可以把某些“键”从系统中删除。

大多数客户端都遵循相同的规则。你可以在memcached的主页上查看一些通用的说明和最佳实践。

如果你真的想深入了解,可以看看源代码。这里有个头部注释:

"""
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.
"""

撰写回答