Reference¶
- class pylibmc.Client(servers[, binary=False, username=None, password=None, behaviors=None])¶
Interface to a set of memcached servers.
servers is a sequence of strings specifying the servers to use.
binary specifies whether or not to use the binary protocol to talk to the memcached servers.
username and password are credentials for SASL authentication. It requires support in libmemcached, and binary=True. Test for local support with pylibmc.support_sasl.
behaviors, if given, is passed to
Client.set_behaviors()after initialization.Supported transport mechanisms are TCP, UDP and UNIX domain sockets. The default transport type is TCP.
To specify UDP, the server address should be prefixed with
"udp:", as in"udp:127.0.0.1". A UDP client is write-only, see below.To specify UNIX domain socket, the server address must start with a slash, as in
"/run/foo.sock".Mixing transport types is prohibited by
pylibmcas this is not supported by libmemcached.UDP is write-only
libmemcached runs a UDP client in noreply mode (
get_behaviors()["_noreply"]is1and cannot be turned off): commands are sent as datagrams and the server’s answers are never read. So a UDP client can only send.Reads raise
pylibmc.NotSupportedError:get,gets,get_multi,key in mc,mc[key],touchandget_stats.Calls whose result would be taken from the server’s answer also raise
pylibmc.NotSupportedError, rather than return something made up:incr,decr,incr_multi,casandexists. Nothing is sent.Writes are fire and forget:
set,add,replace,append,prepend,delete,set_multi,add_multi,delete_multiandflush_allreturnTrue(set_multiandadd_multireturn an empty list), and that means sent, not stored.addreturnsTruealthough the key exists, anddeletealthough it does not; the server’s refusal is not seen. Use a TCP client to read the result.The rules also hold for clones and for the pools in
pylibmc.pools.
memcached must listen for UDP, which is off by default since memcached 1.5.6: start it with
-U <port>(it can serve TCP and UDP at once, for examplememcached -p 11211 -U 11211). A datagram has to hold the whole command, so large values do not work: about 5 kB arrives, but values of 100 kB fail withpylibmc.WriteError(the limit is what the operating system accepts in one datagram, not measured per platform), and on the binary protocol the server is then marked failed and later calls raisepylibmc.ServerDownuntil the retry timeout has passed (measured with libmemcached 1.0.18).- clone() clone¶
Clone client, making new connections as necessary.
The clone has the same servers, behaviors (including
pickle_protocol), binary protocol setting and SASL credentials, and is of the same class, so overriddenserialize()anddeserialize()methods apply to it too. Attributes a subclass sets on the instance (for example in its own__init__) are not copied.ClientPoolandThreadMappedPoolhand out clones, so their clients authenticate like the original.
Note
Every data method below (
get,gets,set,add,replace,append,prepend,cas,delete,touch,exists,incr,decr,get_multi,set_multi,add_multi,delete_multiandincr_multi) takes a keyword-only master_key argument. The default,None, is the usual behavior. When given, libmemcached hashes the master key instead of the item key to pick the server, but the item is still stored and fetched under its own key, so you must pass the same master key to read, change and delete an item as to write it. See Master keys.The master key is checked like a key (text or bytes, not empty, shorter than 250 bytes;
ValueErrororTypeErrorotherwise). It is passed down with the call and never stored on the client. The key_prefix argument of the*_multimethods applies to the item keys only, not to the master key.touchworks with or without a master key.Note
Keys are
str(encoded as UTF-8) orbytesand must be shorter than 250 bytes. With the text protocol a key must also not contain whitespace or control characters (any byte at or below0x20, or0x7f); withbinary=Trueany byte is allowed. A bad key raisesValueErrorin every method (and ininandclient[key]), before anything is sent. See Key checks and the verify_keys behavior.- get(key[, default, master_key=None]) value¶
Get key if it exists, otherwise default. If default is not given, it defaults to
None.
- get_multi(keys[, key_prefix=None, master_key=None]) values¶
Get each of the keys in sequence keys.
If key_prefix is given, specifies a string to prefix each of the values in keys with.
Returns a mapping of each unprefixed key to its corresponding value in memcached. If a key doesn’t exist, no corresponding key is set in the returned mapping.
- exists(key[, master_key=None]) bool¶
Trueif key is stored,Falseif not, without the value being sent over the network, which saves the transfer for large values. Any stored value counts,Noneand empty values included. As the value is never fetched,deserialize()is not called, so a value it would turn into a miss (CacheMiss) counts as present. The empty key isFalse, a bad key raises like it does inget(), and a server error (a server that is down, say) raises.key in clientstill callsget()and discards the value; it does not useexists, for the reason in the note.Note
memcached has no command that only checks for a key, so libmemcached asks with an
addof an empty item whose expiry is already in the past. A present key is left as it was and a missing key stays missing, but to the server a miss is a store of an item that expires at once. It counts in thecmd_setandtotal_itemsstatistics, and when the cache is full it can evict a live item: with memcached 1.6.45 and a full cache of small items, every miss evicted one. A server run with-M(no evictions) answers a miss on a full cache with an out-of-memory error, whichexistsraises. A proxy in front of memcached sees a write. Where that matters, useget().With the
buffer_requestsor_noreplybehavior on,existsfetches the item and drops the value instead, because libmemcached’s answer cannot be trusted there: withbuffer_requestson the binary protocol it reads the reply of an earlier buffered command, and with_noreplylibmemcached 1.0.18 can wait forever. It then answers whatget()would, including not seeing a store still in the buffer. A UDP client raisesNotSupportedError, see above.
- set(key, value[, time=0, min_compress_len=0, compress_level=-1, master_key=None]) success¶
Set key to value.
- Parameters:
key – Key to use
value – Value to set
time – Time until expiry
min_compress_len – Minimum length before compression is triggered
If time is given, it specifies the number of seconds until key will expire. Default behavior is to never expire (equivalent of specifying
0).Warning
The time argument is passed on to memcached as is, and memcached interprets it in two ways. A value up to and including 30 days (
60 * 60 * 24 * 30= 2592000 seconds) is a number of seconds from now. A larger value is taken as an absolute Unix timestamp. Sotime=30 * 86400 + 1is a moment in January 1970, and the key is already expired when it is stored (the call still returnsTrue). To expire a key more than 30 days from now, passint(time.time()) + seconds.A negative value raises
ValueError, as does one that does not fit in 32 bits. (Before 1.8.0 a negative value was silently turned into a huge one, and the text protocol then expired the key immediately while the binary protocol stored it without expiry.) Usedelete()to remove a key.The same rules apply to every method below that takes time.
If min_compress_len is given, it specifies the maximum number of actual bytes stored in memcached before compression is used. Default behavior is to never compress (which is what
0means). See Compression.If compress_level is given, it specifies the compression level for the data. It accepts the same values as the
zlibfamily, for which zlib.Z_BEST_SPEED and zlib.Z_BEST_COMPRESSION are commonly used constants. It accepts values between [0, 9] inclusively.
- set_multi(mapping[, time=0, key_prefix=None, min_compress_len, compress_level, master_key=None]) failed_keys¶
Set multiple keys as given by mapping. time is the same as for
set(), including the 30 day limit for relative times.If key_prefix is specified, each of the keys in mapping is prepended with this value.
Returns a list of keys which were not set for one reason or another, without their optional key prefix.
- add(key, value[, time, min_compress_len, compress_level, master_key=None]) success¶
Sets key if it does not exist. time is the same as for
set().
- replace(key, value[, time, min_compress_len, compress_level, master_key=None]) success¶
Sets key only if it already exists. time is the same as for
set().
- append(key, value[, master_key=None]) success¶
Append value to key (i.e.,
m[k] = m[k] + v).Note
Uses memcached’s appending support, and therefore should never be used on keys which may be compressed or non-string values.
- prepend(key, value[, master_key=None]) success¶
Prepend value to key (i.e.,
m[k] = v + m[k]).Note
Uses memcached’s prepending support, and therefore should never be used on keys which may be compressed or non-string values.
- incr(key[, delta=1, initial=None, expire=0, master_key=None]) value¶
Increment value at key by delta.
Returns the new value for key, after incrementing.
Works for both strings and integer types. delta is 0 to
2**32 - 1(ValueErrorbelow,OverflowErrorabove).Without initial, a missing key raises
pylibmc.NotFound. With initial (0 to2**64 - 1), a missing key is created with that value in the same round trip, and the call returns initial: delta is not added to a key that was just created. An existing key is incremented and initial is ignored. This replacesadd(key, 0)followed byincr(key), which is two round trips and races.expire is the expiry time of a key that initial creates, interpreted like time in
set()(0 means never). It does not change the expiry of an existing key, and without initial it must be 0 (ValueErrorotherwise).4294967295is reserved by the protocol and raisesValueError.Note
initial needs the binary protocol (
binary=True). memcached’s text protocol has no way to create a key inincr, so on a text-protocol client initial raisespylibmc.NotSupportedErrorbefore anything is sent.Note
A key created by initial holds the number as ASCII digits with no pylibmc flags, so
get()returns it asbytes(b"10"), notint. Useint(mc.get(key)), or keep using the return value ofincr.
- decr(key[, delta=1, initial=None, expire=0, master_key=None]) value¶
Decrement value at key by delta.
Returns the new value for key, after decrementing.
Works for both strings and integer types, but will never decrement below zero. initial and expire work as in
incr(): a missing key is created with initial and initial is returned.
- gets(key[, master_key=None]) -> (value, cas_id)¶
Get key and its compare-and-swap ID if it exists, otherwise
(None, None).The so-called CAS token or ID is used with
cas()to update a value with the guarantee that no other value was written in between.
- cas(key, value, cas[, time=0, min_compress_len=0, compress_level=-1, master_key=None]) swapped¶
Set key to value if key CAS token is cas.
- Parameters:
key – Key to use
value – Value to set
cas – Compare-and-swap token from
gets()time – Time until expiry
min_compress_len – Minimum length before compression is triggered
compress_level – zlib compression level, 0 to 9, or -1 for the default
If time is given, it specifies the number of seconds until key will expire. Default behavior is to never expire (equivalent of specifying
0). Times over 30 days are absolute timestamps and negative times raiseValueError, seeset().min_compress_len and compress_level work exactly as they do for
set(), and a compressed value is read back by any client the same way. (Before 1.8.0,cascould not compress and did not take them.)Returns
Falseif the token no longer matches, that is, if the key was written by someone else aftergets().
- delete(key[, master_key=None]) deleted¶
Delete key if it exists.
Returns
Trueif the key was deleted,Falseotherwise (as is the case if it wasn’t set in the first place.)
- delete_multi(keys[, key_prefix=None, master_key=None]) deleted¶
Delete each of key in the sequence keys.
- Parameters:
keys – Sequence of keys to delete
key_prefix – Prefix for the keys to delete
Returns
Trueif all keys were successfully deleted,Falseotherwise (as is the case if it wasn’t set in the first place.)
- touch(key, time[, master_key=None]) touched¶
Touch a given key and set its expiry time to time seconds.
- Parameters:
key – Key to touch
time – Number of seconds until the key expires.
Times over 30 days are absolute Unix timestamps, and a negative time raises
ValueError; seeset().Returns
Trueif the key was successfully touched.Falseif the key did not exist (so touching is not possible.)
- disconnect_all()¶
Disconnect from all servers and reset internal state.
Exposed mainly for compatibility with python-memcached, as there really is no logical reason to do this.
- flush_all() success¶
Flush all data from all servers.
Note
This clears the specified memcacheds fully and entirely.
- get_stats() [name, stats, ...]¶
Retrieve statistics from each of the connected memcached instances.
Returns a list of two-tuples of the format
(name, stats).stats is a mapping of statistics item names to their values. Whether or not a key exists depends on the version of libmemcached and memcached used.
- serialize(value) bytestring, flag¶
Serialize a Python value to bytes bytestring and an integer flag field for storage in memcached. The default implementation has special cases for bytes, text, ints/longs and bools, and falls back to pickle for all other objects. A bool is stored as the integer
1or0with an extra flag (bit 31), so it comes back as a bool; a reader that does not know the flag, such aspython-memcached, sees the integer. Override this method to use a custom serialization format, or otherwise modify the behavior.flag is exposed by the memcached protocol. It adds flexibility in terms of encoding schemes: for example, objects a and b of different types may coincidentally encode to the same bytestring, just so long as they encode with different values of flag. If distinct values always encode to different byte strings (for example, when serializing all values with pickle), flag can simply be set to a constant.
- deserialize(bytestring, flag) value¶
Deserialize bytestring, stored with flag, back to a Python object. Override this method (in concert with
serialize) to use a custom serialization format, or otherwise modify the behavior.Raise
CacheMissin order to simulate a cache miss for the relevant key, i.e.,getwill return None andget_multiwill omit the key from the returned mapping. This can be used to recover gracefully from version skew (e.g., retrieving a value that was pickled by a different, incompatible code version).