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

Jon*_*ior 90 python memcached

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

我一直在网上搜索试图在python-memcached模块上找到一些好的文档,但我能找到的只是MySQL网站上的这个例子,其方法的文档并不是很好.

Oli*_*Oli 144

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

大多数客户遵循相同的规则.您可以阅读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.
"""
Run Code Online (Sandbox Code Playgroud)

  • `mc`是Memcache Client对象,它表示memcached连接. (9认同)
  • @Kevin混合理论这整个问题是关于[python-memcached](http://www.tummy.com/Community/software/python-memcached/).这就是提供`memcache`的原因. (4认同)

Fel*_*Yan 43

我建议你pylibmc改用.

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

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

  • 他们现在都支持Python3. (10认同)
  • 请注意,`pylibmc`在Python 3上不起作用. (3认同)
  • 虽然如此,`python-memcached`也不支持Python 3.pylibmc目前正在准备支持Python 3的版本 (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
    =============
...
------------------------------------------
Run Code Online (Sandbox Code Playgroud)