ó
,áÒNc           @   si  d  Z  d d l Z d d l Z d d l Z d d l Z d d l Z y d d l Z Wn e k
 rq d d l Z n Xd d l	 m
 Z
 d „  Z e a d „  Z y  d d l m Z m Z e Z Wn  e k
 rÜ e Z d „  Z n Xy d d l m Z Wn! e k
 rd d l m Z n Xd	 Z d
 Z d Z d Z d Z d d Z d e f d „  ƒ  YZ d e f d „  ƒ  YZ y d d l m  Z  Wn' e k
 r¦d e! f d „  ƒ  YZ  n Xd Z" d Z# d e  f d „  ƒ  YZ$ d e! f d „  ƒ  YZ% d „  Z& e' d k red a( d GHe& ƒ  d  GHHd! g g Z) d" e j* k rOe) j+ e j, j- e j. ƒ  d# ƒ g ƒ n  xâe) D]ÚZ/ e$ e/ d$ d% ƒZ0 d& „  Z1 d' „  Z2 d( e! f d) „  ƒ  YZ3 e2 d* d+ ƒ e2 d, d- ƒ e2 d. e4 d% d >ƒ ƒ r'd/ Ge0 j5 d. ƒ räd0 GHn d1 GHt( d% a( d2 GHe0 j6 d. ƒ e7 k rd0 GHn d1 GHt( d% a( n  d3 Ge0 j8 d* d, g ƒ GHd4 Ge1 e0 j6 d5 ƒ ƒ GHe3 ƒ  Z9 e2 d6 e9 ƒ d7 Ge0 j: d, d% ƒ Z; e; d8 k r—d0 GHn d1 GHt( d% a( d9 Ge0 j< d, d% ƒ Z; e; d- k rÐd0 GHn d1 GHt( d% a( e j= j> ƒ  d: Ge j= j> ƒ  y e0 j? d; d% ƒ Z; Wn e$ j@ k
 r0ZA d0 GHn Xd1 GHt( d% a( d< Gy e0 j? d= d% ƒ Z; Wn e$ j@ k
 rwZA d0 GHn Xd1 GHt( d% a( d> Gy e0 j? d? e d% ƒ Z; Wn% e$ jB k
 rÌZA d1 GHt( d% a( n Xd0 GHy e0 j? d? e d? d% ƒ Z; Wn e$ jB k
 rZA d0 GHn Xd1 GHt( d% a( d@ Gy e0 j? dA d% ƒ Z; Wn e$ jC k
 rSZA d0 Gn Xd1 Gt( d% a( y# e0 j? dB e jD dC ƒ d% ƒ Z; Wn d1 Gt( d% a( n Xd0 Gd d l Z e jE dD ƒ ZF y# e0 j? eF e jD dC ƒ d% ƒ Z; Wn e$ jB k
 rúd0 GHn Xd1 GHt( d% a( dE Ge0 j? dF d? e ƒ Z; e0 j6 dF ƒ e7 k r@d0 Gn d1 Gt( d% a( e0 j? dF d? e dG ƒ Z; e0 j6 dF ƒ e7 k r…d0 GHn d1 GHt( d% a( dH Ge0 jG ƒ  e0 jH i d? dF 6dI dJ 6ƒ ZI eI g  k rÝd1 GHt( d% a( n d0 GHdK Ge0 jG ƒ  e0 jJ i d? dF 6dI dJ 6ƒ ZK eK d% k r+d1 GHt( d% a( n d0 GHqVWt( d k rUdL GHe jL d% ƒ n  e jL d ƒ n  d S(M   sÒ  
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.
iÿÿÿÿN(   t   crc32c         C   s   t  |  ƒ d @d ?d @p d S(   Nl   ÿÿ i   iÿ  i   (   R    (   t   key(    (    s   ./memcache.pyt   cmemcache_hash9   s    c           C   s
   t  a d S(   s1   Use the old python-memcache server hash function.N(   R    t   serverHashFunction(    (    (    s   ./memcache.pyt   useOldServerHashFunction=   s    (   t   compresst
   decompressc         C   s   t  d ƒ ‚ d  S(   NsG   received compressed data but I don't support compression (import error)(   t   _Error(   t   val(    (    s   ./memcache.pyR   H   s    (   t   StringIOs-   Sean Reifschneider <jafo-memcached@tummy.com>s   1.48s$   Copyright (C) 2003 Danga Interactives"   Python Software Foundation Licenseiú   i   R   c           B   s   e  Z RS(    (   t   __name__t
   __module__(    (    (    s   ./memcache.pyR   _   s   t   _ConnectionDeadErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   c   s   (   t   localR   c           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   l   s   i   i   t   Clientc           B   s`  e  Z d  Z d6 Z d7 Z d8 Z d9 Z d Z d e f d „  ƒ  YZ	 d e	 f d	 „  ƒ  YZ
 d
 e	 f d „  ƒ  YZ d e	 f d „  ƒ  YZ d e	 f d „  ƒ  YZ d e f d „  ƒ  YZ d d e j e j d: d: e e e e e d „ Z d „  Z d „  Z d: d „ Z d „  Z d „  Z d „  Z d „  Z d „  Z  d „  Z! d „  Z" d „  Z# d d d „ Z$ d d  „ Z% d d! „ Z& d d" „ Z' d# „  Z( d d d$ „ Z) d d d% „ Z* d d d& „ Z+ d d d' „ Z, d d d( „ Z- d d d) „ Z. d* „  Z/ d d d d+ „ Z0 d, „  Z1 d d- „ Z2 d. „  Z3 d/ „  Z4 d0 „  Z5 d d1 „ Z6 d: d2 „ Z7 d: d3 „ Z8 d4 „  Z9 d d5 „ Z: RS(;   s¤  
    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
    i   i    i   i   i
   t   MemcachedKeyErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   ‘   s   t   MemcachedKeyLengthErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   “   s   t   MemcachedKeyCharacterErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   •   s   t   MemcachedKeyNoneErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   —   s   t   MemcachedKeyTypeErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   ™   s   t   MemcachedStringEncodingErrorc           B   s   e  Z RS(    (   R
   R   (    (    (    s   ./memcache.pyR   ›   s   c         C   sß   t  j |  ƒ | |  _ |
 |  _ | |  _ |  j | ƒ i  |  _ | |  _ |  j ƒ  | |  _	 | |  _
 | |  _ | |  _ | |  _ | |  _ |	 |  _ t ƒ  } y% |  j
 | d |  j	 ƒ} t |  _ Wn t k
 rÚ t |  _ n Xd S(   s  
        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.
        t   protocolN(   R   t   __init__t   debugt
   dead_retryt   socket_timeoutt   set_serverst   statst	   cache_cast	   reset_cast   pickleProtocolt   picklert	   unpicklert   persistent_loadt   persistent_idt   server_max_key_lengtht   server_max_value_lengthR	   t   Truet   picklerIsKeywordt	   TypeErrort   False(   t   selft   serversR   R   R   R    t   ploadt   pidR#   R$   R   R   R   t   file(    (    s   ./memcache.pyR   ž   s*    !					
								c         C   s   i  |  _  d S(   sö   
        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(   t   cas_ids(   R)   (    (    s   ./memcache.pyR   Ù   s    c      	   C   sH   g  | D]* } t  | |  j d |  j d |  j ƒ^ q |  _ |  j ƒ  d S(   sd  
        Set 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.
        R   R   N(   t   _HostR   R   R   R*   t   _init_buckets(   R)   R*   t   s(    (    s   ./memcache.pyR   ã   s    
7c   	      C   s  g  } x|  j  D]ø } | j ƒ  s( q n  | j t j k rY d | j | j | j f } n d | j | j f } | s… | j	 d ƒ n | j	 d | ƒ i  } | j
 | | f ƒ | j } xM | ƒ  } | sÝ | j ƒ  d k rá Pn  | j d d ƒ } | d | | d <q» q W| S(	   s¸  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   unix:%s (%s)R   s   stats t   ENDt    i   i   (   R*   t   connectt   familyt   sockett   AF_INETt   ipt   portt   weightt   addresst   send_cmdt   appendt   readlinet   stript   split(	   R)   t	   stat_argst   dataR1   t   namet
   serverDataR>   t   lineR   (    (    s   ./memcache.pyt	   get_statsò   s(     		 c   	      C   s5  g  } x(|  j  D]} | j ƒ  s( q n  | j t j k rY d | j | j | j f } n d | j | j f } i  } | j	 | | f ƒ | j
 d ƒ | j } xŒ | ƒ  } | sÃ | j ƒ  d k rÇ Pn  | j d d ƒ } | d j d d ƒ } | d | k ri  | | d <n  | d | | d | d <q¡ q W| S(	   Ns
   %s:%s (%s)s   unix:%s (%s)s   stats itemsR2   R3   i   i   t   :(   R*   R4   R5   R6   R7   R8   R9   R:   R;   R=   R<   R>   R?   R@   (	   R)   RB   R1   RC   RD   R>   RE   t   itemt   slab(    (    s   ./memcache.pyt	   get_slabs  s*     		 !c         C   sD   x= |  j  D]2 } | j ƒ  s" q
 n  | j d ƒ | j d ƒ q
 Wd S(   s2   Expire all data currently in the memcache servers.t	   flush_allt   OKN(   R*   R4   R<   t   expect(   R)   R1   (    (    s   ./memcache.pyRK   +  s
     c         C   s$   |  j  r  t j j d | ƒ n  d  S(   Ns   MemCached: %s
(   R   t   syst   stderrt   write(   R)   t   str(    (    s   ./memcache.pyt   debuglog2  s    	c         C   s6   | |  j  k r d |  j  | <n |  j  | c d 7<d  S(   Ni   (   R   (   R)   t   func(    (    s   ./memcache.pyt   _statlog6  s    c         C   s!   x |  j  D] } d | _ q
 Wd S(   sC   
        Reset every host in the pool to an "alive" state.
        i    N(   R*   t	   deaduntil(   R)   R1   (    (    s   ./memcache.pyt   forget_dead_hosts<  s    c         C   sK   g  |  _  x; |  j D]0 } x' t | j ƒ D] } |  j  j | ƒ q) Wq Wd  S(   N(   t   bucketsR*   t   rangeR:   R=   (   R)   t   servert   i(    (    s   ./memcache.pyR0   C  s    	c         C   s”   t  | t ƒ r | \ } } n t | ƒ } xc t t j ƒ D]R } |  j | t |  j ƒ } | j ƒ  rp | | f St t	 | ƒ t	 | ƒ ƒ } q: Wd S(   N(   NN(   t
   isinstancet   tupleR   RX   R   t   _SERVER_RETRIESRW   t   lenR4   RQ   t   None(   R)   R   t
   serverhashRZ   RY   (    (    s   ./memcache.pyt   _get_serverI  s    
 c         C   s"   x |  j  D] } | j ƒ  q
 Wd  S(   N(   R*   t   close_socket(   R)   R1   (    (    s   ./memcache.pyt   disconnect_allW  s    t    c         C   sÄ  |  j  d ƒ |  j | | ƒ \ } } g  } d } xí | j ƒ  D]ß } g  }	 |	 j }
 | d k r‹ xL | | D] } |
 d | | f ƒ qj Wn# x  | | D] } |
 d | ƒ q– Wy | j d j |	 ƒ ƒ Wq> t j k
 r} d } t	 | t
 ƒ rÿ | d } n  | j | ƒ | j | ƒ q> Xq> Wx | D] } | | =q(Wx„ | j ƒ  D]v \ } } y" x | D] } | j d ƒ q\WWqFt j k
 r»} t	 | t
 ƒ r¥| d } n  | j | ƒ d } qFXqFW| S(	   sÕ  
        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

        t   delete_multii   s   delete %s %d
s   delete %s
Rd   i    t   DELETEDN(   RT   t   _map_and_prefix_keyst   iterkeysR=   R_   t	   send_cmdst   joinR6   t   errorR[   R\   t	   mark_deadt	   iteritemsRM   (   R)   t   keyst   timet
   key_prefixt   server_keyst   prefixed_to_orig_keyt   dead_serverst   rcRY   t   bigcmdRP   R   t   msg(    (    s   ./memcache.pyRe   [  s@    	  c         C   s  |  j  | ƒ |  j | ƒ \ } } | s, d S|  j d ƒ | d	 k rd | d k rd d | | f } n
 d | } yP | j | ƒ | j ƒ  } | r¦ | j ƒ  d
 k r¦ d S|  j d t | ƒ ƒ Wn? t	 j
 k
 rÿ } t | t ƒ rï | d } n  | j | ƒ n Xd S(   sã   Deletes 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.
        @rtype: int
        i    t   deletes   delete %s %ds	   delete %sRf   t	   NOT_FOUNDi   s-   Delete expected DELETED or NOT_FOUND, got: %sN(   s   DELETEDRx   (   t	   check_keyRa   RT   R_   R<   R>   R?   RR   t   reprR6   Rk   R[   R\   Rl   (   R)   R   Ro   RY   t   cmdRE   Rv   (    (    s   ./memcache.pyRw     s(    
 	 c         C   s   |  j  d | | ƒ S(   s;  
        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
        t   incr(   t	   _incrdecr(   R)   R   t   delta(    (    s   ./memcache.pyR|   º  s    c         C   s   |  j  d | | ƒ S(   sV  
        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
        t   decr(   R}   (   R)   R   R~   (    (    s   ./memcache.pyR   Ô  s    
c         C   sÜ   |  j  | ƒ |  j | ƒ \ } } | s, d S|  j | ƒ d | | | f } yI | j | ƒ | j ƒ  } | d  k s† | j ƒ  d k rŠ d  St | ƒ SWn@ t j	 k
 r× } t
 | t ƒ rÆ | d } n  | j | ƒ d  SXd  S(   Ni    s   %s %s %dRx   i   (   Ry   Ra   RT   R<   R>   R_   R?   t   intR6   Rk   R[   R\   Rl   (   R)   R{   R   R~   RY   RE   Rv   (    (    s   ./memcache.pyR}   à  s"      c         C   s   |  j  d | | | | ƒ S(   s·   
        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
        t   add(   t   _set(   R)   R   R   Ro   t   min_compress_len(    (    s   ./memcache.pyR   ñ  s    	c         C   s   |  j  d | | | | ƒ S(   sÐ   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
        R=   (   R‚   (   R)   R   R   Ro   Rƒ   (    (    s   ./memcache.pyR=   ü  s    	c         C   s   |  j  d | | | | ƒ S(   sÖ   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
        t   prepend(   R‚   (   R)   R   R   Ro   Rƒ   (    (    s   ./memcache.pyR„     s    	c         C   s   |  j  d | | | | ƒ S(   sÐ   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
        t   replace(   R‚   (   R)   R   R   Ro   Rƒ   (    (    s   ./memcache.pyR…     s    	c         C   s   |  j  d | | | | ƒ S(   sR  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.
        t   set(   R‚   (   R)   R   R   Ro   Rƒ   (    (    s   ./memcache.pyR†     s    c         C   s   |  j  d | | | | ƒ S(   s–  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 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.
        t   cas(   R‚   (   R)   R   R   Ro   Rƒ   (    (    s   ./memcache.pyR‡   8  s    c   
      C   s  t  | ƒ } | r" |  j | ƒ n  i  } i  } xË | D]Ã } t | t ƒ r€ t | d ƒ } |  j | d | | f ƒ \ } }	 n% t | ƒ } |  j | | ƒ \ } }	 |  j | d | ƒ| sÄ q5 n  | | k rÝ g  | | <n  | | j |	 ƒ | | |	 <q5 W| | f S(   s¤   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.


        i   i    t   key_extra_len(   R^   Ry   R[   R\   RQ   Ra   R=   (
   R)   t   key_iterableRp   Rˆ   Rq   Rr   t   orig_keyt   str_orig_keyRY   R   (    (    s   ./memcache.pyRg   V  s&    &c      
   C   s  |  j  d ƒ |  j | j ƒ  | ƒ \ } } g  } g  } xþ | j ƒ  D]ð }	 g  }
 |
 j } yŒ xo | |	 D]c } |  j | | | | ƒ } | r¹ | d | | d | | d | d f ƒ qg | j | | ƒ qg W|	 j d j |
 ƒ ƒ WqD t j k
 r3} t	 | t
 ƒ r| d } n  |	 j | ƒ | j |	 ƒ qD XqD Wx | D] }	 | |	 =q?W| s`| j ƒ  Sx¦ | j ƒ  D]˜ \ }	 } yD x= | D]5 } |	 j ƒ  } | d k r§qƒqƒ| j | | ƒ qƒWWqmt t j f k
 r} t	 | t
 ƒ rô| d } n  |	 j | ƒ qmXqmW| S(   sà  
        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'}
            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

        t	   set_multis   set %s %d %d %d
%s
i    i   i   Rd   t   STORED(   RT   Rg   Rh   R=   t   _val_to_store_infoRi   Rj   R6   Rk   R[   R\   Rl   Rn   Rm   R>   R   (   R)   t   mappingRo   Rp   Rƒ   Rq   Rr   Rs   t	   notstoredRY   Ru   RP   R   t
   store_infoRv   Rn   RE   (    (    s   ./memcache.pyRŒ   }  sL    )		  
 c         C   sŒ  d } t  | t ƒ r nÞ t  | t ƒ rG | t j O} d | } d } n¯ t  | t ƒ rv | t j O} d | } d } n€ | t j O} t ƒ  } |  j	 r° |  j
 | d |  j ƒ} n |  j
 | |  j ƒ } |  j rÝ |  j | _ n  | j | ƒ | j ƒ  } t | ƒ } | rQt rQ| | k rQt | ƒ } t | ƒ | k  rQ| t j O} | } qQn  |  j d k ryt | ƒ |  j k ryd S| t | ƒ | f S(   s—   
           Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself.
        i    s   %dR   (   R[   RQ   R€   R   t   _FLAG_INTEGERt   longt
   _FLAG_LONGt   _FLAG_PICKLER	   R&   R   R   R"   t   dumpt   getvalueR^   t   _supports_compressR   t   _FLAG_COMPRESSEDR$   (   R)   R   Rƒ   t   flagsR-   R   t   lvt   comp_val(    (    s   ./memcache.pyRŽ   Õ  s<    
	
				 c            s²   ˆ j  ˆ ƒ ˆ j ˆ ƒ \ ‰ ‰ ˆ s, d S‡  ‡ ‡ ‡ ‡ ‡ ‡ f d †  } y | ƒ  SWnS t k
 r­ y ˆ j ƒ  | ƒ  SWn) t t j f k
 r¨ } ˆ j | ƒ n Xd SXd  S(   Ni    c       	      s$  ˆ j  ˆ ƒ ˆ j ˆ ˆ  ƒ }  |  s) d Sˆ d k r’ ˆ ˆ j k r] ˆ j d ˆ ˆ ˆ ˆ  ƒ Sd ˆ ˆ |  d ˆ |  d ˆ j ˆ |  d f } n( d ˆ ˆ |  d ˆ |  d |  d f } y$ ˆ j | ƒ ˆ j d ƒ d k SWn? t j k
 r} t | t	 ƒ r| d } n  ˆ j
 | ƒ n Xd S(	   Ni    R‡   R†   s   %s %s %d %d %d %d
%si   i   s   %s %s %d %d %d
%sR   (   RT   RŽ   R.   R‚   R<   RM   R6   Rk   R[   R\   Rl   (   R‘   t   fullcmdRv   (   Rƒ   R   R)   R{   RY   R   Ro   (    s   ./memcache.pyt   _unsafe_set	  s(     % (   Ry   Ra   R   t   _get_socketR6   Rk   Rl   (   R)   R{   R   R   Ro   Rƒ   Rž   Rv   (    (   Rƒ   R   R)   R{   RY   R   Ro   s   ./memcache.pyR‚     s    !
c            s¯   ˆ  j  ˆ ƒ ˆ  j ˆ ƒ \ ‰ ‰ ˆ s, d  S‡  ‡ ‡ ‡ f d †  } y | ƒ  SWnY t k
 rª y ˆ j ƒ  ru | ƒ  Sd  SWn) t t j f k
 r¥ } ˆ j | ƒ n Xd  SXd  S(   Nc             s  ˆ  j  ˆ ƒ yÂ ˆ j d ˆ ˆ f ƒ d  }  } } } ˆ d k r‚ ˆ  j ˆ ƒ \ }  } } } |  rš ˆ  j rš | ˆ  j |  <qš n ˆ  j ˆ ƒ \ }  } } |  s¤ d  Sz ˆ  j ˆ | | ƒ } Wd  ˆ j d ƒ XWnF t	 t
 j f k
 r} t | t ƒ r| d } n  ˆ j | ƒ d  SX| S(   Ns   %s %st   getsR2   i   (   RT   R<   R_   t   _expect_cas_valueR   R.   t   _expectvaluet   _recv_valueRM   R   R6   Rk   R[   R\   Rl   (   t   rkeyRš   t   rlent   cas_idt   valueRv   (   R)   R{   RY   R   (    s   ./memcache.pyt   _unsafe_get2  s(     (   Ry   Ra   R_   R   R4   R6   Rk   Rl   (   R)   R{   R   R¨   Rv   (    (   R)   R{   R   RY   s   ./memcache.pyt   _get,  s    c         C   s   |  j  d | ƒ S(   sP   Retrieves a key from the memcache.

        @return: The value or None.
        t   get(   R©   (   R)   R   (    (    s   ./memcache.pyRª   Y  s    c         C   s   |  j  d | ƒ S(   sp   Retrieves a key from the memcache. Used in conjunction with 'cas'.

        @return: The value or None.
        R    (   R©   (   R)   R   (    (    s   ./memcache.pyR    `  s    c         C   s¶  |  j  d ƒ |  j | | ƒ \ } } g  } x… | j ƒ  D]w } y" | j d d j | | ƒ ƒ Wq8 t j k
 r® } t | t ƒ r‘ | d } n  | j	 | ƒ | j
 | ƒ q8 Xq8 Wx | D] } | | =qº Wi  } xÞ | j ƒ  D]Ð } y‚ | j ƒ  }	 xo |	 rd|	 d k rd|  j | |	 ƒ \ }
 } } |
 d k	 rU|  j | | | ƒ } | | | |
 <n  | j ƒ  }	 qö WWqÞ t t j f k
 r­} t | t ƒ r| d } n  | j	 | ƒ qÞ XqÞ W| S(   s2  
        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.

        t	   get_multis   get %sR3   i   R2   N(   RT   Rg   Rh   R<   Rj   R6   Rk   R[   R\   Rl   R=   R>   R¢   R_   R£   R   (   R)   Rn   Rp   Rq   Rr   Rs   RY   Rv   t   retvalsRE   R¤   Rš   R¥   R   (    (    s   ./memcache.pyR«   g  s8    &"  c         C   sp   | s | j  ƒ  } n  | rh | d  d k rh | j ƒ  \ } } } } } | t | ƒ t | ƒ t | ƒ f Sd Sd  S(   Ni   t   VALUE(   NNNN(   R>   R@   R€   R_   (   R)   RY   RE   t   respR¤   Rš   R^   R¦   (    (    s   ./memcache.pyR¡   ¯  s    "c         C   sp   | s | j  ƒ  } n  | rh | d  d k rh | j ƒ  \ } } } } t | ƒ } t | ƒ } | | | f Sd Sd  S(   Ni   R­   (   NNN(   R>   R@   R€   R_   (   R)   RY   RE   R®   R¤   Rš   R^   R¥   (    (    s   ./memcache.pyR¢   ¹  s    c   	      C   sq  | d 7} | j  | ƒ } t | ƒ | k rJ t d t | ƒ | f ƒ ‚ n  t | ƒ | k ri | d  } n  | t j @r… t | ƒ } n  | d k s  | t j k r© | } nÄ | t j @rÅ t | ƒ } n¨ | t j @rá t	 | ƒ } nŒ | t j
 @r\yC t | ƒ } |  j | ƒ } |  j r$|  j | _ n  | j ƒ  } Wqmt k
 rX} |  j d | ƒ d  SXn |  j d | ƒ | S(   Ni   s#   received %d bytes when expecting %diþÿÿÿi    s   Pickle error: %s
s   unknown flags on get: %x
(   t   recvR^   R   R   R™   R   R’   R€   R”   R“   R•   R	   R    R!   t   loadt	   ExceptionRR   R_   (	   R)   RY   Rš   R¥   t   bufR   R-   R    t   e(    (    s   ./memcache.pyR£   Å  s6    
		c         C   s  t  | t ƒ r | d } n  | s4 t j d ƒ ‚ n  t  | t ƒ rU t j d ƒ ‚ n  t  | t ƒ sv t j d ƒ ‚ n  t  | t ƒ r|  j	 d k rÆ t
 | ƒ | |  j	 k rÆ t j d |  j	 ƒ ‚ n  xG | D]< } t | ƒ d k  s÷ t | ƒ d k rÍ t j d	 ƒ ‚ qÍ qÍ Wn  d
 S(   sµ  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)
        i   s   Key is Nones`   Keys must be str()'s, not unicode.  Convert your unicode strings using mystring.encode(charset)!s   Key must be str()'si    s   Key length is > %si!   i   s   Control characters not allowedN(   R[   R\   R   R   t   unicodeR   RQ   R   t
   basestringR#   R^   R   t   ordR   (   R)   R   Rˆ   t   char(    (    s   ./memcache.pyRy   è  s$    	 	$i   i   i   i   N(;   R
   R   t   __doc__R•   R’   R”   R™   R]   R±   R   R   R   R   R   R   t   picklet   Picklert	   UnpicklerR_   t   SERVER_MAX_KEY_LENGTHt   SERVER_MAX_VALUE_LENGTHt   _DEAD_RETRYt   _SOCKET_TIMEOUTR(   R   R   R   RF   RJ   RK   RR   RT   RV   R0   Ra   Rc   Re   Rw   R|   R   R}   R   R=   R„   R…   R†   R‡   Rg   RŒ   RŽ   R‚   R©   Rª   R    R«   R¡   R¢   R£   Ry   (    (    (    s   ./memcache.pyR   t   sj   5	
	!								B		'X	.)	-		H
	#R/   c           B   s†   e  Z d  e e d „ Z d „  Z d „  Z d „  Z d „  Z d „  Z	 d „  Z
 d „  Z d	 „  Z d
 „  Z d „  Z d „  Z d „  Z RS(   i    c         C   sK  | |  _  | |  _ | |  _ t | t ƒ r< | \ } |  _ n	 d |  _ t j d | ƒ } | sr t j d | ƒ } n  | s t j d | ƒ } n  | s¦ t d | ƒ ‚ n  | j	 ƒ  } | j
 d ƒ d k rã t j |  _ | d |  _ nI t j |  _ | d	 |  _ t | j
 d
 d ƒ ƒ |  _ |  j |  j f |  _ d |  _ d  |  _ d |  _ d  S(   Ni   s   ^(?P<proto>unix):(?P<path>.*)$s5   ^(?P<proto>inet):(?P<host>[^:]+)(:(?P<port>[0-9]+))?$s%   ^(?P<host>[^:]+)(:(?P<port>[0-9]+))?$s'   Unable to parse connection string: "%s"t   protot   unixt   patht   hostR9   iË+  i    Rd   (   R   R   R   R[   R\   R:   t   ret   matcht
   ValueErrort	   groupdictRª   R6   t   AF_UNIXR5   R;   R7   R8   R€   R9   RU   R_   t   buffer(   R)   RÃ   R   R   R   t   mt   hostData(    (    s   ./memcache.pyR     s2    					 		c         C   s$   |  j  r  t j j d | ƒ n  d  S(   Ns   MemCached: %s
(   R   RN   RO   RP   (   R)   RQ   (    (    s   ./memcache.pyRR   *  s    	c         C   s/   |  j  r" |  j  t j ƒ  k r" d Sd |  _  d S(   Ni   i    (   RU   Ro   (   R)   (    (    s   ./memcache.pyt   _check_dead.  s    	c         C   s   |  j  ƒ  r d Sd S(   Ni   i    (   RŸ   (   R)   (    (    s   ./memcache.pyR4   4  s    c         C   s;   |  j  d |  | f ƒ t j ƒ  |  j |  _ |  j ƒ  d  S(   Ns    MemCache: %s: %s.  Marking dead.(   RR   Ro   R   RU   Rb   (   R)   t   reason(    (    s   ./memcache.pyRl   9  s    c         C   sö   |  j  ƒ  r d  S|  j r  |  j St j |  j t j ƒ } t | d ƒ rZ | j |  j ƒ n  y | j |  j	 ƒ Wno t j
 k
 r˜ } |  j d | ƒ d  St j k
 rß } t | t ƒ rÆ | d } n  |  j d | d ƒ d  SX| |  _ d |  _ | S(   Nt
   settimeouts   connect: %si   Rd   (   RÌ   R_   R6   R5   t   SOCK_STREAMt   hasattrRÎ   R   R4   R;   t   timeoutRl   Rk   R[   R\   RÉ   (   R)   R1   Rv   (    (    s   ./memcache.pyRŸ   >  s(    	  		c         C   s&   |  j  r" |  j  j ƒ  d  |  _  n  d  S(   N(   R6   t   closeR_   (   R)   (    (    s   ./memcache.pyRb   R  s    	c         C   s   |  j  j | d ƒ d  S(   Ns   
(   R6   t   sendall(   R)   R{   (    (    s   ./memcache.pyR<   W  s    c         C   s   |  j  j | ƒ d S(   s(    cmds already has trailing 
's applied N(   R6   RÓ   (   R)   t   cmds(    (    s   ./memcache.pyRi   Z  s    c         C   sŒ   |  j  } |  j j } x[ t rr | j d ƒ } | d k r= Pn  | d ƒ } | se |  j ƒ  t ƒ  ‚ n  | | 7} q W| | d |  _  | |  S(   Ns   
i    i   i   (   RÉ   R6   R¯   R%   t   findRb   R   (   R)   R²   R¯   t   indexRB   (    (    s   ./memcache.pyR>   ^  s    		
c         C   s6   |  j  ƒ  } | | k r2 |  j d | | f ƒ n  | S(   Ns2   while expecting '%s', got unexpected response '%s'(   R>   RR   (   R)   t   textRE   (    (    s   ./memcache.pyRM   o  s
    	c         C   s‘   |  j  j } |  j } xd t | ƒ | k  r{ | t | t | ƒ d ƒ ƒ } | | 7} | s t d t | ƒ | f ƒ ‚ q q W| | |  _ | |  S(   Ni   s9   Read %d bytes, expecting %d, read returned 0 length bytes(   R6   R¯   RÉ   R^   t   maxR   (   R)   R¥   t   self_socket_recvR²   t   foo(    (    s   ./memcache.pyR¯   v  s    	
c         C   se   d } |  j  r d |  j  } n  |  j t j k rP d |  j d |  j d | f Sd |  j | f Sd  S(   NRd   s    (dead until %d)s   inet:%s:%d%si    i   s	   unix:%s%s(   RU   R5   R6   R7   R;   (   R)   t   d(    (    s   ./memcache.pyt   __str__‚  s    	(   R
   R   R¾   R¿   R   RR   RÌ   R4   Rl   RŸ   Rb   R<   Ri   R>   RM   R¯   RÜ   (    (    (    s   ./memcache.pyR/     s   !											c          C   sS   d d  l  }  d d  l } d g } t | d d ƒ} i | d 6} |  j | d | ƒS(   Niÿÿÿÿs   127.0.0.1:11211R   i   t   mct   globs(   t   doctestt   memcacheR   t   testmod(   Rß   Rà   R*   RÝ   RÞ   (    (    s   ./memcache.pyt   _doctest  s
    	t   __main__i    s   Testing docstrings...s   Running tests:s   127.0.0.1:11211s	   --do-unixs   memcached.socketR   i   c         C   s+   t  |  t ƒ s# d |  t |  ƒ f Sd |  S(   Ns   %s (%s)s   %s(   R[   Rµ   t   type(   R   (    (    s   ./memcache.pyt   to_s¡  s    c         C   se   d t  |  ƒ t  | ƒ f Gt j |  | ƒ t j |  ƒ } | | k rN d GHd Sd GHt d a d Sd  S(   Ns   Testing set/get {'%s': %s} ...RL   i   t   FAILi    (   Rå   RÝ   R†   Rª   t   failures(   R   R   t   newval(    (    s   ./memcache.pyt   test_setget¥  s     
t	   FooStructc           B   s#   e  Z d  „  Z d „  Z d „  Z RS(   c         C   s   d |  _  d  S(   Nt   baz(   t   bar(   R)   (    (    s   ./memcache.pyR   ³  s    c         C   s   d S(   Ns   A FooStruct(    (   R)   (    (    s   ./memcache.pyRÜ   µ  s    c         C   s#   t  | t ƒ r |  j | j k Sd S(   Ni    (   R[   Rê   Rì   (   R)   t   other(    (    s   ./memcache.pyt   __eq__·  s    (   R
   R   R   RÜ   Rî   (    (    (    s   ./memcache.pyRê   ²  s   		t   a_strings   some random stringt
   an_integeri*   R“   s   Testing delete ...RL   Ræ   s   Checking results of delete ...s   Testing get_multi ...s   Testing get(unknown value) ...t   unknown_valuet	   foostructs   Testing incr ...i+   s   Testing decr ...s   Testing sending spaces...s   this has spacess%   Testing sending control characters...s   thishascontrol characterss"   Testing using insanely long key...t   as'   Testing sending a unicode-string key...u   keyhereu   as   utf-8s   V\u4f1a
p0
.s>   Testing using a value larger than the memcached value limit...t   keyheret   aaas.   Testing set_multi() with no memcacheds runningt   bt   keytheres1   Testing delete_multi() with no memcacheds runnings   *** THERE WERE FAILED TESTS(M   R¸   RN   R6   Ro   t   osRÄ   t   cPickleR¹   t   ImportErrort   binasciiR    R   R   R   t   zlibR   R   R%   R˜   R(   t	   cStringIOR	   t
   __author__t   __version__t   __copyright__t   __license__R¼   R½   R±   R   R   t	   threadingR   t   objectR¾   R¿   R   R/   Râ   R
   Rç   t
   serverListt   argvR=   RÂ   Rj   t   getcwdR*   RÝ   Rå   Ré   Rê   R“   Rw   Rª   R_   R«   t   fR|   t   xR   t   stdoutt   flushR†   R   Rv   R   R   t   encodet   loadsR1   Rc   RŒ   t   errorsRe   t   rett   exit(    (    (    s   ./memcache.pyt   <module>,   sN  		

ÿ ÿ ÿ •‡	(		
 
 	 
 
	 
	 
 	 
 
# #	 
 
 

 
 	