Current File : //lib/python3.9/site-packages/__pycache__/memcache.cpython-39.pyc
a

^�Lb3��@sdZddlmZddlZddlmZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZej
rlddlZnddlZdd�Zeadd�Ze�d	�Zd
ZdZdZd
ZdZdZGdd�de�ZGdd�de�ZdZdZGdd�de	j �Z!Gdd�de"�Z#dd�Z$dS)a�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.

�)�print_functionN)�BytesIOcCst�|�d@d?d@pdS)Nl���i��)�binascii�crc32)�key�r	�,/usr/lib/python3.9/site-packages/memcache.py�cmemcache_hashDsrcCs
tjadS)z1Use the old python-memcache server hash function.N)rr�serverHashFunctionr	r	r	r
�useOldServerHashFunctionIsr
s
[!-~�-�]+$z-Sean Reifschneider <jafo-memcached@tummy.com>z1.59z$Copyright (C) 2003 Danga Interactivez"Python Software Foundation License�ic@seZdZdS)�_ErrorN��__name__�
__module__�__qualname__r	r	r	r
rasrc@seZdZdS)�_ConnectionDeadErrorNrr	r	r	r
resr��cs eZdZdZdZdZdZdZdZdZ	Gdd	�d	e
�ZGd
d�de�ZGdd
�d
e�Z
Gdd�de�ZGdd�de�ZGdd�de
�Zddejejejejddddeedddf�fdd�	Zdd�Zdd�Zdd�Zd d!�Zdid"d#�Zd$d%�Zd&d'�Z d(d)�Z!d*d+�Z"d,d-�Z#d.d/�Z$d0d1�Z%d2d3�Z&d4d5�Z'djd7d8�Z(dkd9d:�Z)dld;d<�Z*dmd=d>�Z+dnd?d@�Z,dodAdB�Z-dpdCdD�Z.dqdEdF�Z/drdGdH�Z0dsdIdJ�Z1dtdKdL�Z2dudMdN�Z3dvdOdP�Z4dQdR�Z5dwdSdT�Z6dUdV�Z7dxdWdX�Z8dYdZ�Z9d[d\�Z:d]d^�Z;dyd_d`�Z<dzdadb�Z=d{dcdd�Z>dedf�Z?d|dgdh�Z@�ZAS)}�Clienta�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.).
        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
    r���r�
c@seZdZdS)zClient.MemcachedKeyErrorNrr	r	r	r
�MemcachedKeyError�src@seZdZdS)zClient.MemcachedKeyLengthErrorNrr	r	r	r
�MemcachedKeyLengthError�src@seZdZdS)z!Client.MemcachedKeyCharacterErrorNrr	r	r	r
�MemcachedKeyCharacterError�src@seZdZdS)zClient.MemcachedKeyNoneErrorNrr	r	r	r
�MemcachedKeyNoneError�src@seZdZdS)zClient.MemcachedKeyTypeErrorNrr	r	r	r
�MemcachedKeyTypeError�sr c@seZdZdS)z#Client.MemcachedStringEncodingErrorNrr	r	r	r
�MemcachedStringEncodingError�sr!rNFTcs�tt|���||_||_|
|_||_|�|�i|_||_	|�
�||_||_||_
||_||_||_||_|	|_|
|_|jdur�t|_||_|jdur�t|_t�}z|j
||jd�}d|_Wnty�d|_Yn0dS)a�Create a new Client object with the given list of servers.

        @param servers: C{servers} is passed to L{set_servers}.
        @param debug: whether to display error messages when a server
        can't be contacted.
        @param pickleProtocol: number to mandate protocol used by
        (c)Pickle.
        @param pickler: optional override of default Pickler to allow
        subclassing.
        @param unpickler: optional override of default Unpickler to
        allow subclassing.
        @param pload: optional persistent_load function to call on
        pickle loading.  Useful for cPickle since subclassing isn't
        allowed.
        @param pid: optional persistent_id function to call on pickle
        storing.  Useful for cPickle since subclassing isn't allowed.
        @param dead_retry: number of seconds before retrying a
        blacklisted server. Default to 30 s.
        @param socket_timeout: timeout in seconds for all calls to a
        server. Defaults to 3 seconds.
        @param cache_cas: (default False) If true, cas operations will
        be cached.  WARNING: This cache is not expired internally, if
        you have a long-running process you will need to expire it
        manually via client.reset_cas(), or the cache can grow
        unlimited.
        @param server_max_key_length: (default SERVER_MAX_KEY_LENGTH)
        Data that is larger than this will not be sent to the server.
        @param server_max_value_length: (default
        SERVER_MAX_VALUE_LENGTH) Data that is larger than this will
        not be sent to the server.
        @param flush_on_reconnect: optional flag which prevents a
        scenario that can cause stale data to be read: If there's more
        than one memcached server and the connection to one is
        interrupted, keys that mapped to that server will get
        reassigned to another. If the first server comes back, those
        keys will map to it again. If it still has its data, get()s
        can read stale data that was overwritten on another
        server. This flag is off by default for backwards
        compatibility.
        @param check_keys: (default True) If True, the key is checked
        to ensure it is the correct length and composed of the right
        characters.
        N�ZprotocolTF)�superr�__init__�debug�
dead_retry�socket_timeout�flush_on_reconnect�set_servers�stats�	cache_cas�	reset_cas�do_check_key�pickleProtocol�pickler�	unpickler�
compressor�decompressor�persistent_load�
persistent_id�server_max_key_length�SERVER_MAX_KEY_LENGTH�server_max_value_length�SERVER_MAX_VALUE_LENGTHr�picklerIsKeyword�	TypeError)�self�serversr%r.r/r0r1r2Zpload�pidr5r7r&r'r+r(Z
check_keys�file��	__class__r	r
r$�s:2



zClient.__init__cCsLt|t�r2t|dtj�rH|d|d�d�fSnt|tj�rH|�d�S|S)Nrr�utf8)�
isinstance�tuple�six�	text_type�encode�r;rr	r	r
�_encode_key�s

zClient._encode_keycGsvtjr|�d�n|}|d|g}|rFtjr2|�d�}|�d�|�|�|rT|�d�|rl|�d�|�|�d�|�S)N�utf-8� s noreply�)rD�PY3rF�append�extend�join)r;�cmdr�headers�noreply�args�	cmd_bytes�fullcmdr	r	r
�_encode_cmd�s






zClient._encode_cmdcCs
i|_dS)z�Reset the cas cache.

        This is only used if the Client() object was created with
        "cache_cas=True".  If used, this cache does not expire
        internally, so it can grow unbounded if you do not clear it
        yourself.
        N)�cas_ids�r;r	r	r
r,szClient.reset_cascs �fdd�|D��_���dS)ahSet the pool of servers used by this client.

        @param servers: an array of servers.
        Servers can be passed in two forms:
            1. 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.

        c	s&g|]}t|�j�j�j�jd��qS))r&r'r()�_Hostr%r&r'r()�.0�srXr	r
�
<listcomp>#s
��z&Client.set_servers.<locals>.<listcomp>N)r<�
_init_buckets)r;r<r	rXr
r)s
�zClient.set_serversc	Cs�g}|jD]�}|��sq
|jtjkr:d|j|j|jf}n2|jtjkr\d|j|j|jf}nd|j	|jf}|s||�
d�n|�
d|�i}|�||f�|j}|�}|r�|�
d���dkr�q
|�
d��dd	�}|d	||d
<q�q
|S)a�Get statistics from each of the servers.

        @param stat_args: Additional arguments to pass to the memcache
            "stats" command.

        @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.
        �
%s:%s (%s)�[%s]:%s (%s)�unix:%s (%s)r*zstats �ascii�END� rr)r<�connect�family�socket�AF_INET�ip�port�weight�AF_INET6�address�send_cmdrM�readline�decode�strip�split)	r;Z	stat_args�datar[�name�
serverDatarn�liner*r	r	r
�	get_stats)s*
zClient.get_statsc	Cs$g}|jD�]}|��sq
|jtjkr<d|j|j|jf}n2|jtjkr^d|j|j|jf}nd|j	|jf}i}|�
||f�|�d�|j}|�}|r�|�
�dkr�q
|�dd�}|�d�s�|�d	�r�|d||d
<q�|d
�dd�}|d|v�ri||d<|d||d|d
<q�q
|S)
Nr^r_r`zstats slabsrbrcrzSTAT active_slabszSTAT total_mallocedr�:r)r<rdrerfrgrhrirjrkrlrMrmrnrprq�
startswith�	r;rrr[rsrtrnru�itemZslabr	r	r
�get_slab_statsOs0
zClient.get_slab_statsc	Cs�g}|jD]�}|��sq
|jtjkr:d|j|j|jf}n2|jtjkr\d|j|j|jf}nd|j	|jf}i}|�
||f�|�d�|j}|�}|r�|�
�dkr�q
|�dd�}|d�d	d�}|d|vr�i||d<|d||d|d<q�q
|S)
Nr^r_r`zstats itemsrbrcrrrw)r<rdrerfrgrhrirjrkrlrMrmrnrprqryr	r	r
�	get_slabsns,

zClient.get_slabscCs"|jD]}|��sq|��qdS)z7Expire all data in memcache servers that are reachable.N)r<rd�flush�r;r[r	r	r
�	flush_all�s
zClient.flush_allcCs|jrtj�d|�dS�NzMemCached: %s
�r%�sys�stderr�write�r;�strr	r	r
�debuglog�szClient.debuglogcCs,||jvrd|j|<n|j|d7<dS)Nr)r*)r;�funcr	r	r
�_statlog�s
zClient._statlogcCs|jD]
}d|_qdS)z1Reset every host in the pool to an "alive" state.rN)r<�	deaduntilr~r	r	r
�forget_dead_hosts�s
zClient.forget_dead_hostscCs2g|_|jD] }t|j�D]}|j�|�qqdS�N)�bucketsr<�rangerjrM)r;�server�ir	r	r
r]�s
zClient._init_bucketscCs�t|t�r|\}}nt|�}|js&dSttj�D]Z}|j|t|j�}|��r\||fSt	|�t	|�}t|t
j�r�|�d�}t|�}q0dS)N)NNra)
rBrCrr�r�r�_SERVER_RETRIES�lenrdr�rDrErF)r;r�
serverhashr�r�r	r	r
�_get_server�s



zClient._get_servercCs|jD]}|��qdSr�)r<�close_socketr~r	r	r
�disconnect_all�s
zClient.disconnect_all�cCsx|�d�|�||�\}}g}d}t�|�D]�}	g}
|
j}|durLt|�}nd}||	D]}
|�d|
||d�}||�qXz|	�d�|
��Wq,t	j
y�}z6d}t|t�r�|d}|	�
|�|�|	�WYd}~q,d}~00q,|r�|S|D]
}	||	=q�t�|�D]p\}	}z|D]}
|	�d��qWnJt	j
�yn}z.t|t��rL|d}|	�
|�d}WYd}~n
d}~00�q|S)	a3Delete multiple keys in the memcache doing just one query.

        >>> notset_keys = mc.set_multi({'a1' : 'val1', 'a2' : 'val2'})
        >>> mc.get_multi(['a1', 'a2']) == {'a1' : 'val1','a2' : '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}.
        @param noreply: optional parameter instructs the server to not send the
            reply.
        @return: 1 if no failure in communication with any memcacheds.
        @rtype: int
        �delete_multirN�delete�
rKr�DELETED)r��_map_and_prefix_keysrD�iterkeysrMr�rV�	send_cmdsrOrf�errorrBrC�	mark_dead�	iteritems�expect)r;�keys�time�
key_prefixrR�server_keys�prefixed_to_orig_key�dead_servers�rcr��bigcmdr�rQrrP�msgr	r	r
r��sJ
�



"
zClient.delete_multicCs|�ddgd|||�S)aFDeletes a key from the memcache.

        @return: Nonzero on success.
        @param time: number of seconds any subsequent set / update commands
        should fail. Defaults to None for no delay.
        @param noreply: optional parameter instructs the server to not send the
            reply.
        @rtype: int
        r��	NOT_FOUNDr���_deletetouch�r;rr�rRr	r	r
r�s
�z
Client.deletecCs|�dgd|||�S)a#Updates the expiration time of a key in memcache.

        @return: Nonzero on success.
        @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 noreply: optional parameter instructs the server to not send the
            reply.
        @rtype: int
        sTOUCHED�touchr�r�r	r	r
r�s
zClient.touchc
Cs�|�|�}|jr|�|�|�|�\}}|s0dS|�|�|durLt|�}nd}|�||||�}zP|�|�|rvWdS|��}	|	r�|	�	�|vr�WdS|�
d|d�|�|	f�WnBtj
y�}
z(t|
t�r�|
d}
|�|
�WYd}
~
n
d}
~
00dS)Nrrz%s expected %s, got: %rs or )rHr-�	check_keyr�r�r�rVrmrnrpr�rOrfr�rBrCr�)r;ZexpectedrPrr�rRr�rQrUrur�r	r	r
r�$s4




�

 zClient._deletetouchcCs|�d|||�S)a�Increment value for C{key} by C{delta}

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

        @param noreply: optional parameter instructs the server to not send the
        reply.

        @return: New value after incrementing, no None for noreply or error.
        @rtype: int
        �incr��	_incrdecr�r;r�deltarRr	r	r
r�AszClient.incrcCs|�d|||�S)aDecrement value for C{key} by C{delta}

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

        @param noreply: optional parameter instructs the server to not send the
        reply.

        @return: New value after decrementing,  or None for noreply or error.
        @rtype: int
        �decrr�r�r	r	r
r�bszClient.decrc	
Cs�|�|�}|jr|�|�|�|�\}}|s0dS|�|�|�||t|�|�}z@|�|�|rdWdS|��}|dus�|�	�dkr�WdSt
|�WStjy�}z*t
|t�r�|d}|�|�WYd}~dSd}~00dS)Nr�r)rHr-r�r�r�rVr�rmrnrp�intrfr�rBrCr�)	r;rPrr�rRr�rUrur�r	r	r
r�ts*






zClient._incrdecrcCs|�d|||||�S)z�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
        �add��_set�r;r�valr��min_compress_lenrRr	r	r
r��s	z
Client.addcCs|�d|||||�S)z�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
        rMr�r�r	r	r
rM�s	z
Client.appendcCs|�d|||||�S)z�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
        �prependr�r�r	r	r
r��s	zClient.prependcCs|�d|||||�S)z�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
        �replacer�r�r	r	r
r��s	zClient.replacecCs|�d|||||�S)a�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 compressor
        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 yields a larger string
        than the input, then it is discarded. For backwards
        compatibility, this parameter defaults to 0, indicating don't
        ever try to compress.

        @param noreply: optional parameter instructs the server to not
        send the reply.
        �setr�r�r	r	r
r��s z
Client.setcCs|�d|||||�S)aCheck and set (CAS)

        Sets a key to a given value in the memcache if it hasn't been
        altered since last fetched. (See L{gets}).

        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 compressor
        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 yields a larger string
        than the input, then it is discarded. For backwards
        compatibility, this parameter defaults to 0, indicating don't
        ever try to compress.

        @param noreply: optional parameter instructs the server to not
        send the reply.
        �casr�r�r	r	r
r��s#z
Client.cascCsF|�|�}t|�}|r&|jr&|�|�i}i}|D�]}t|t�r�|\}}|�|�}t|tj�sxt|�}tj	rx|�
d�}|}	|�|||f�\}
}|d}nD|�|�}t|tj�s�t|�}tj	r�|�
d�}|}	|�||�\}
}|dur�|j||d�|j�r|j|	|d�|
�sq2|
|v�r&g||
<||
�|�|||<q2||fS)z�Map keys to the servers they will reside on.

        Compute the mapping of server (_Host instance) -> list of keys to
        stuff onto that server, as well as the mapping of prefixed key
        -> original key.
        rArN)�
key_extra_len)
rHr�r-r�rBrCrD�binary_typer�rLrFr�rM)r;Zkey_iterabler�r�r�r�Zorig_keyr�rZbytes_orig_keyr�r	r	r
r��sJ







�




zClient._map_and_prefix_keyscCs�|�d�|�t�|�|�\}}g}g}	t�|�D]�}
g}|j}z�||
D]b}
|�|||
|�}|r�|\}}}d|||f}|�d|
||d|d�}||�qJ|	�||
�qJ|
�d�|��Wq2t	j
�y}z2t|t�r�|d}|
�
|�|�|
�WYd}~q2d}~00q2|�r|	S|D]}
||
=�q |�s@t|���St�|�D]�\}
}z2|D](}
|
��dk�rp�qXn|	�||
��qXWnJtt	j
f�y�}z*t|t��r�|d}|
�
|�WYd}~n
d}~00�qJ|	S)	a%
Sets multiple keys in the memcache doing just one query.

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


        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
            >>> keys = mc.get_multi(['subspace_key1', 'subspace_key2'])
            >>> keys == {'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 compressor
            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 yields a
            larger string than the input, then it is discarded. For
            backwards compatibility, this parameter defaults to 0,
            indicating don't ever try to compress.

        @param noreply: optional parameter instructs the server to not
            send the reply.

        @return: List of keys which failed to be stored [ memcache out
           of memory, etc. ].

        @rtype: list
        �	set_multi�%d %d %dr�r�rKrN�STORED)r�r�rDr�rM�_val_to_store_inforVr�rOrfr�rBrCr��listr�r�rnr)r;�mappingr�r�r�rRr�r�r�Z	notstoredr�r�r�r�
store_info�flags�len_valr�rQrUr�r�r	r	r
r�As^<

�
�

�


"
$zClient.set_multic	Csbd}t|�}|tjkrn�|tjkr8|tjO}|�d�}n�|tkrh|tjO}d|}tj	rb|�d�}d}n�tj
r�t|t�r�|tj
O}t|�}tj	r�|�d�}d}nV|tjO}t�}|jr�|j||jd�}n|�||j�}|jr�|j|_|�|�|��}t|�}|�r4||k�r4|�|�}t|�|k�r4|tjO}|}|jdk�rTt|�|jk�rTdS|t|�|fS)z�Transform val to a storable representation.

        Returns a tuple of the flags, the length of the new value, and
        the new value itself.
        rrIz%drar")�typerDr�rEr�
_FLAG_TEXTrFr��
_FLAG_INTEGERrL�PY2rB�long�
_FLAG_LONGr��_FLAG_PICKLErr9r/r.r4�dump�getvaluer�r1�_FLAG_COMPRESSEDr7)	r;r�r�r�Zval_typer>r/�lvZcomp_valr	r	r
r��sN










�zClient._val_to_store_infoc	
s�������jr��������\���s0dS��������fdd�}z|�WSty�z���rv|�WYSWn4ttjfy�}z��|�WYd}~n
d}~00YdS0dS)Nrc
s�����dkr0��jvr0��d������S�����}|sDdS|\}}}�dkrnd|�|�j�f}nd|�|f}����|�d|�}z(��|��r�WdS�jddd	�dkWStjy�}z(t	|t
�r�|d
}��|�WYd}~n
d}~00dS)Nr�r�rz%d %d %d %dr�r�Tr���raise_exceptionr)r�rWr�r�rVrmr�rfr�rBrCr�)r�r�r�Zencoded_valrQrUr��rPrr�rRr;r�r�r�r	r
�_unsafe_set�s6
�
��

 z Client._set.<locals>._unsafe_set)	rHr-r�r�r�_get_socketrfr�r�)	r;rPrr�r�r�rRr�r�r	r�r
r��s 

 zClient._setc
s�������jr��������\���s0dS����fdd�}z|�WSty�z���rn|�WYSWYdSttjfy�}z��|�WYd}~n
d}~00YdS0dS)Nc
s ����z�tjr��d�n�}d�|d�f�}��|�d}}}}�dkr~�j�dd�\}}}}|r��jr�|�j|<n�j	�dd�\}}}|s�WdSz ��
�||�}W�jddd�n�jddd�0WnJtt
jf�y}z*t|t�r�|d}��|�WYd}~dSd}~00|S)	NrIrKrJ�getsTr��ENDr)r�rDrLrFrOrm�_expect_cas_valuer+rW�_expectvalue�_recv_valuer�rrfr�rBrCr�)rTrU�rkeyr��rlen�cas_id�valuer��rPrr;r�r	r
�_unsafe_get.s4

�
�$

z Client._get.<locals>._unsafe_get)	rHr-r�r�rrdrfr�r�)r;rPrr�r�r	r�r
�_get&s"

" zClient._getcCs|�d|�S)zPRetrieves a key from the memcache.

        @return: The value or None.
        �get�r�rGr	r	r
r�\sz
Client.getcCs|�d|�S)zpRetrieves a key from the memcache. Used in conjunction with 'cas'.

        @return: The value or None.
        r�r�rGr	r	r
r�cszClient.getscCsl|�d�|�||�\}}g}t�|�D]r}z dd�||�}|�|�Wq(tjy�}z2t|t	�rp|d}|�
|�|�|�WYd}~q(d}~00q(|D]
}||=q�i}	t�|�D]�}z\|��}
|
�r|
dk�r|�
||
�\}}}
|du�r|�|||
�}||	||<|��}
q�Wq�ttjf�yd}z*t|t	��rF|d}|�
|�WYd}~q�d}~00q�|	S)aRetrieves 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_multi [ 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 returned
        dictionary will not have it present.
        �	get_multisget rJrNr�)r�r�rDr�rOrmrfr�rBrCr�rMrnr�r�r)r;r�r�r�r�r�r�rUr�Zretvalsrur�r�r�r�r	r	r
r�js>7
�

"
"zClient.get_multic	CsT|s|�|�}|rL|dd�dkrL|��\}}}}}|t|�t|�t|�fSdSdS)N��VALUE)NNNN�rnrqr�)	r;r�rur��respr�r�r�r�r	r	r
r��s
zClient._expect_cas_valuec	CsT|s|�|�}|rL|dd�dkrL|��\}}}}t|�}t|�}|||fSdSdS)Nr�r�)NNNr�)	r;r�rur�r�r�r�r�r�r	r	r
r��s

zClient._expectvaluec	
CsV|d7}|�|�}t|�|kr2tdt|�|f��t|�|krJ|dd�}|tj@rj|�|�}|tjM}|dkrx|}n�|tj@r�|�d�}n�|tj@r�t	|�}n�|tj
@r�tjr�t	|�}nt
|�}n�|tj@�r8z,t|�}|�|�}|jr�|j|_|��}Wn6t�y4}z|�d|�WYd}~dSd}~00n|�d|�td|��|S)	Nrz#received %d bytes when expecting %d���rrIzPickle error: %s
zunknown flags on get: %x
zUnknown flags on get: %x)�recvr�rrr�r2r�ror�r�r�rDrLr�r�rr0r3�load�	Exceptionr��
ValueError)	r;r�r�r��bufr�r>r0�er	r	r
r��sD

�








zClient._recv_valuecCs�t|t�r|d}|dur$t�d��|durB|dur>t�d��dSt|tj�sXt�d��|jdkr�t|�||jkr�t�	d|j��t
�|�s�t�d	|��dS)
a�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)
        rNzKey is Noner�rzKey is emptyzKey must be a binary stringzKey length is > %sz-Control/space characters not allowed (key=%r))
rBrCrrrDr�r r5r�r�valid_key_chars_re�matchr)r;rr�r	r	r
r�s(




��
�zClient.check_key)N)Nr�F)NF)rF)rF)rF)rF)F)rrF)rrF)rrF)rrF)rrF)rrF)rr�rF)rF)r�)NF)NF)r)Brrr�__doc__r�r�r�r�r�r�r�rrrrr r!�pickleZPicklerZ	Unpickler�zlib�compress�
decompress�_DEAD_RETRY�_SOCKET_TIMEOUTr$rHrVr,r)rvr{r|rr�r�r�r]r�r�r�r�r�r�r�r�r�r�rMr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
__classcell__r	r	r?r
rms|�T

&
J



!






"
%C�
w<
26
^


)rc@s�eZdZdeedfdd�Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
d dd�Zd!dd�Zdd�Zdd�Zdd�ZdS)"rYrcCs@||_||_||_||_t|t�r.|\}|_nd|_t�d|�}|sPt�d|�}|s`t�d|�}|spt�d|�}|s�t	d|��|�
�}|�d�dkr�tj
|_|d	|_nz|�d�d
kr�tj|_|d|_t|�d�p�d
�|_|j|jf|_n6tj|_|d|_t|�d��pd
�|_|j|jf|_d|_d|_d|_d|_dS)Nrz^(?P<proto>unix):(?P<path>.*)$z=^(?P<proto>inet6):\[(?P<host>[^\[\]]+)\](:(?P<port>[0-9]+))?$z5^(?P<proto>inet):(?P<host>[^:]+)(:(?P<port>[0-9]+))?$z%^(?P<host>[^:]+)(:(?P<port>[0-9]+))?$z'Unable to parse connection string: "%s"�protoZunix�pathZinet6�hostrii�+rrK)r&r'r%r(rBrCrj�rer�r��	groupdictr�rfZAF_UNIXrerlrkrhr�rirgr��flush_on_next_connect�buffer)r;rr%r&r'r(�mZhostDatar	r	r
r$-sJ
��

z_Host.__init__cCs|jrtj�d|�dSr�r�r�r	r	r
r�Zsz_Host.debuglogcCs"|jr|jt��krdSd|_dS�Nrr)r�r�rXr	r	r
�_check_dead^sz_Host._check_deadcCs|��rdSdSr
)r�rXr	r	r
rddsz
_Host.connectcCs:|�d||f�t��|j|_|jr.d|_|��dS)Nz MemCache: %s: %s.  Marking dead.r)r�r�r&r�r(rr�)r;�reasonr	r	r
r�is
z_Host.mark_deadc
Cs�|��rdS|jr|jSt�|jtj�}t|d�r>|�|j�z|�|j�Wn|tj	y�}z|�
d|�WYd}~dSd}~0tjy�}z.t|t
�r�|d}|�
d|�WYd}~dSd}~00||_d|_|j�r�|��d|_|S)N�
settimeoutzconnect: %srrKr)rrfreZSOCK_STREAM�hasattrr
r'rdrl�timeoutr�r�rBrCrrr})r;r[r�r	r	r
r�ps.

z_Host._get_socketcCs|jr|j��d|_dSr�)rf�closerXr	r	r
r��s
z_Host.close_socketcCs*t|tj�r|�d�}|j�|d�dS)NrAr��rBrDrErFrfZsendall)r;rPr	r	r
rm�s
z_Host.send_cmdcCs&t|tj�r|�d�}|j�|�dS)z'cmds already has trailing 
's applied.rANr)r;Zcmdsr	r	r
r��s
z_Host.send_cmdsFcCs�|j}|jr|jj}ndd�}|�d�}|dkr2qb|d�}|sX|�d�|rTt��ndS||7}q||dd	�|_|d	|�S)
z�Read a line and return it.

        If "raise_exception" is set, raise _ConnectionDeadError if the
        read fails, otherwise return an empty string.
        cSsdS)NrKr	)�bufsizer	r	r
�<lambda>�rKz _Host.readline.<locals>.<lambda>r�r�zconnection closed in readline()r�rN)rrfr��findr�r)r;r�r�r��indexrrr	r	r
rn�s 



z_Host.readlinecCsP|�|�}|jrL||krLtjr6|�d�}|�dd�}n|}|�d||f�|S)NrAr�z.while expecting %r, got unexpected response %r)rnr%rDrLror�)r;�textr�ruZlog_liner	r	r
r��s

�z_Host.expectcCsl|jj}|j}t|�|krR|t|t|�d��}||7}|stdt|�|f��q||d�|_|d|�S)Nrz9Read %d bytes, expecting %d, read returned 0 length bytes)rfr�rr��maxr)r;r�Zself_socket_recvr�Zfoor	r	r
r��s
�z
_Host.recvcCs|�d�|�d�dS)NrsOK)rmr�rXr	r	r
r}�s
z_Host.flushcCsrd}|jrd|j}|jtjkr:d|jd|jd|fS|jtjkr`d|jd|jd|fSd|j|fSdS)Nr�z (dead until %d)zinet:%s:%d%srrzinet6:[%s]:%d%sz	unix:%s%s)r�rerfrgrlrk)r;�dr	r	r
�__str__�s
z
_Host.__str__N)F)F)rrrr�rr$r�rrdr�r�r�rmr�rnr�r�r}rr	r	r	r
rY+s �
-

rYcCsdddl}ddl}dg}|j|dd�}d|i}|j||d�}|��td|f�|jr`t�d�dS)Nrz127.0.0.1:11211r)r%�mc)�globszDoctests: %s)	�doctest�memcacherZtestmodr��printZfailedr��exit)rrr<rr�resultsr	r	r
�_doctest�sr")%r�Z
__future__rr�iorrrfr��	threadingr�r�rDr�ZcPickler�rrr
�compiler��
__author__�__version__Z
__copyright__Z__license__r6r8r�rrr�r�localr�objectrYr"r	r	r	r
�<module>sP-

G5