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

时间:2009-05-15 13:31:57

标签: python memcached

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

我一直在网上搜索试图在python-memcached模块上找到一些好的文档,但我找到的只有this example on the MySQL website,而且其方法的文档也不是很好。

3 个答案:

答案 0 :(得分:143)

这很简单。您使用键和到期时间来写入值。您可以使用键获取值。您可以从系统中过期密钥。

大多数客户遵循相同的规则。您可以阅读the memcached homepage上的通用说明和最佳做法。

如果你真的想深入研究它,我会看一下来源。这是标题评论:

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

答案 1 :(得分:43)

我建议你改用pylibmc

它可以作为python-memcache的替代品,但速度要快得多(因为它是用C语言编写的)。您可以找到方便的文档here

对于这个问题,由于pylibmc只是一个替代品,你仍然可以参考pylibmc的文档来进行python-memcache编程。

答案 2 :(得分:7)

一个好的经验法则:使用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
    =============
...
------------------------------------------