This page contains the Memcache Package documentation.
client module for memcached (memory cache daemon)
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
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.
More detailed documentation is available in the L{Client} class.
Bases: thread._local
Object representing a pool of memcache servers.
See L{memcache} for an overview.
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
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
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
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
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
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.
See docs for L{get_multi} and L{set_multi}.
@return: 1 if no failure in communication with any memcacheds. @rtype: int
Retrieves a key from the memcache.
@return: The value or None.
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.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
@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.
Get statistics from each of the servers.
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
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
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
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.
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:
>>> 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'} TrueCauses 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
Set the pool of servers used by this client.
@param servers: an array of servers. Servers can be passed in two forms:
- Strings of the form C{“host:port”}, which implies a default weight of 1.
2. Tuples of the form C{(“host:port”, weight)}, where C{weight} is an integer weight value.
Bases: gluon.contrib.memcache.memcache.Client