Memcache Documentation

This page contains the Memcache Package documentation.

The memcache Module

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

class gluon.contrib.memcache.memcache.Client(servers, debug=0, pickleProtocol=0, pickler=<built-in function Pickler>, unpickler=<built-in function Unpickler>, pload=None, pid=None)

Bases: thread._local

Object representing a pool of memcache servers.

See L{memcache} for an overview.

In all cases where a key is used, the key can be either:
  1. A simple hashable type (string, integer, etc.).

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache.Client, line 9)

Enumerated list ends without a blank line; unexpected unindent.

2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user’s objects on the same memcache server, so you could use the user’s unique id as the hash value.

@group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog @group Insertion: set, add, replace, set_multi @group Retrieval: get, get_multi @group Integers: incr, decr @group Removal: delete, delete_multi @sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog, set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi

exception MemcachedKeyCharacterError
Bases: gluon.contrib.memcache.memcache.MemcachedKeyError
exception Client.MemcachedKeyError
Bases: exceptions.Exception
exception Client.MemcachedKeyLengthError
Bases: gluon.contrib.memcache.memcache.MemcachedKeyError
exception Client.MemcachedKeyNoneError
Bases: gluon.contrib.memcache.memcache.MemcachedKeyError
exception Client.MemcachedKeyTypeError
Bases: gluon.contrib.memcache.memcache.MemcachedKeyError
exception Client.MemcachedStringEncodingError
Bases: exceptions.Exception
Client.add(key, val, time=0, min_compress_len=0)

Add new key with value.

Like L{set}, but only stores in memcache if the key doesn’t already exist.

@return: Nonzero on success. @rtype: int

Client.append(key, val, time=0, min_compress_len=0)

Append the value to the end of the existing key’s value.

Only stores in memcache if key already exists. Also see L{prepend}.

@return: Nonzero on success. @rtype: int

Client.debuglog(str)
Client.decr(key, delta=1)

Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and new values are capped at 0. If server value is 1, a decrement of 2 returns 0, not -1.

@param delta: Integer amount to decrement by (should be zero or greater). @return: New value after decrementing. @rtype: int

Client.delete(key, time=0)

Deletes a key from the memcache.

@return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @rtype: int

Client.delete_multi(keys, time=0, key_prefix='')

Delete multiple keys in the memcache doing just one query.

>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key2']) == {}
1

This method is recommended over iterated regular L{delete}s as it reduces total latency, since your app doesn’t have to wait for each round-trip of L{delete} before sending the next one.

@param keys: An iterable of keys to clear @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @param key_prefix: Optional string to prepend to each key when sending to memcache.

System Message: ERROR/3 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache, line 17)

Unexpected indentation.
See docs for L{get_multi} and L{set_multi}.

@return: 1 if no failure in communication with any memcacheds. @rtype: int

Client.disconnect_all()
Client.flush_all()
Expire all data currently in the memcache servers.
Client.forget_dead_hosts()
Reset every host in the pool to an “alive” state.
Client.get(key)

Retrieves a key from the memcache.

@return: The value or None.

Client.get_multi(keys, key_prefix='')

Retrieves multiple keys from the memcache doing just one query.

>>> success = mc.set("foo", "bar")
>>> success = mc.set("baz", 42)
>>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
1
>>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
1

This looks up keys ‘pfx_k1’, ‘pfx_k2’, ... . Returned dict will just have unprefixed keys ‘k1’, ‘k2’. >>> mc.get_multi([‘k1’, ‘k2’, ‘nonexist’], key_prefix=’pfx_‘) == {‘k1’ : 1, ‘k2’ : 2} 1

get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields. They’re rotored through str() before being passed off to memcache, with or without the use of a key_prefix. In this mode, the key_prefix could be a table name, and the key itself a db primary key number.

>>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
1
>>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
1

This method is recommended over regular L{get} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn’t have to wait for each round-trip of L{get} before sending the next one.

See also L{set_multi}.

@param keys: An array of keys. @param key_prefix: A string to prefix each key when we communicate with memcache.

System Message: ERROR/3 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache, line 31)

Unexpected indentation.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache.Client.get_multi, line 35)

Block quote ends without a blank line; unexpected unindent.

@return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present.

Client.get_slabs()
Client.get_stats()

Get statistics from each of the servers.

@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying the name of the status field and the string value associated with it. The values are not converted from strings.
Client.incr(key, delta=1)

Sends a command to the server to atomically increment the value for C{key} by C{delta}, or by 1 if C{delta} is unspecified. Returns None if C{key} doesn’t exist on server, otherwise it returns the new value after incrementing.

Note that the value for C{key} must already exist in the memcache, and it must be the string representation of an integer.

>>> mc.set("counter", "20")  # returns 1, indicating success
1
>>> mc.incr("counter")
21
>>> mc.incr("counter")
22

Overflow on server is not checked. Be aware of values approaching 2**32. See L{decr}.

@param delta: Integer amount to increment by (should be zero or greater). @return: New value after incrementing. @rtype: int

Client.prepend(key, val, time=0, min_compress_len=0)

Prepend the value to the beginning of the existing key’s value.

Only stores in memcache if key already exists. Also see L{append}.

@return: Nonzero on success. @rtype: int

Client.replace(key, val, time=0, min_compress_len=0)

Replace existing key with value.

Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}.

@return: Nonzero on success. @rtype: int

Client.set(key, val, time=0, min_compress_len=0)

Unconditionally sets a key to a given value in the memcache.

The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user’s objects on the same memcache server, so you could use the user’s unique id as the hash value.

@return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section “Storage Commands” for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don’t ever try to compress.

Client.set_multi(mapping, time=0, key_prefix='', min_compress_len=0)

Sets multiple keys in the memcache doing just one query.

>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1

This method is recommended over regular L{set} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn’t have to wait for each round-trip of L{set} before sending the next one.

@param mapping: A dict of key/value pairs to set. @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section “Storage Commands” for more info on <exptime>. We default to 0 == cache forever. @param key_prefix: Optional string to prepend to each key when sending to memcache. Allows you to efficiently stuff these keys into a pseudo-namespace in memcache:

System Message: ERROR/3 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache, line 17)

Unexpected indentation.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
>>> len(notset_keys) == 0
True
>>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
True

Causes key ‘subspace_key1’ and ‘subspace_key2’ to be set. Useful in conjunction with a higher-level layer which applies namespaces to data in memcache. In this case, the return result would be the list of notset original keys, prefix not applied.

@param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don’t ever try to compress. @return: List of keys which failed to be stored [ memcache out of memory, etc. ]. @rtype: list

Client.set_servers(servers)

Set the pool of servers used by this client.

@param servers: an array of servers. Servers can be passed in two forms:

System Message: ERROR/3 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache, line 4)

Unexpected indentation.
  1. Strings of the form C{“host:port”}, which implies a default weight of 1.

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/contrib/memcache/memcache.py:docstring of gluon.contrib.memcache.memcache.Client.set_servers, line 8)

Enumerated list ends without a blank line; unexpected unindent.

2. Tuples of the form C{(“host:port”, weight)}, where C{weight} is an integer weight value.

gluon.contrib.memcache.memcache.check_key(key, key_extra_len=0)
Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) Is an unicode string (Raises MemcachedStringEncodingError) Is not a string (Raises MemcachedKeyError) Is None (Raises MemcachedKeyError)

The memcache Package

class gluon.contrib.memcache.MemcacheClient(request, servers, debug=0, pickleProtocol=0, pickler=<built-in function Pickler>, unpickler=<built-in function Unpickler>, pload=None, pid=None)

Bases: gluon.contrib.memcache.memcache.Client

delete(key)
get(key)
increment(key, value=1, time_expire=300)
set(key, value, time_expire=300)

Table Of Contents

Previous topic

Markdown Documentation

Next topic

Simplejson Documentation

This Page