
    sg?                       d Z ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZd Z G d de      ZdZ ed      Z ed      ZdZd	Zd
ZdZdZ dddddd	dddd	dejB                  dZ"dddddZ#dddddddddddddddddZ$ G d  d!      Z% G d" d#e%      Z& G d$ d%e'      Z( G d& d'e)      Z* G d( d)e)      Z+d* Z, G d+ d,      Z-y)-z%Core disk and file backed cache API.
    Nc                 :    | j                   dz   | j                  z   S )zBReturn full name of `func` by adding the module and function name..)
__module____qualname__)funcs    A/var/www/html/venv/lib/python3.12/site-packages/diskcache/core.py	full_namer	      s    ??S 4#4#444    c                       e Zd ZdZd Zd Zy)Constantz%Pretty display of immutable constant.c                 0    t         j                  | |f      S N)tuple__new__)clsnames     r   r   zConstant.__new__   s    }}S4'**r
   c                     d| d   z  S )Nz%sr    selfs    r   __repr__zConstant.__repr__"   s    d1g~r
   N)__name__r   r   __doc__r   r   r   r
   r   r   r      s    /+r
   r   zcache.dbENOVALUNKNOWN            least-recently-storedi   @
   i    wali   i   )
statistics	tag_indexeviction_policy
size_limit
cull_limitsqlite_auto_vacuumsqlite_cache_sizesqlite_journal_modesqlite_mmap_sizesqlite_synchronousdisk_min_file_sizedisk_pickle_protocol)countsizehitsmisses)initgetcullzACREATE INDEX IF NOT EXISTS Cache_store_time ON Cache (store_time)z6SELECT {fields} FROM Cache ORDER BY store_time LIMIT ?zCCREATE INDEX IF NOT EXISTS Cache_access_time ON Cache (access_time)zaccess_time = {now}z7SELECT {fields} FROM Cache ORDER BY access_time LIMIT ?zECREATE INDEX IF NOT EXISTS Cache_access_count ON Cache (access_count)zaccess_count = access_count + 1z8SELECT {fields} FROM Cache ORDER BY access_count LIMIT ?)noner    zleast-recently-usedzleast-frequently-usedc                   T    e Zd ZdZddZd Zd Zd ZefdZ	ddZ
d	 Zeefd
Zd Zy)Diskz@Cache key and value serialization for SQLite database and files.c                 .    || _         || _        || _        y)zInitialize disk instance.

        :param str directory: directory path
        :param int min_file_size: minimum size for file use
        :param int pickle_protocol: pickle protocol for serialization

        N)
_directorymin_file_sizepickle_protocol)r   	directoryr;   r<   s       r   __init__zDisk.__init__j   s     $*.r
   c                 |   d}| j                  |      \  }}t        |      }|t        j                  u rt	        j
                  |      |z  S |t        u r't	        j
                  |j                  d            |z  S |t        u r||z  S |t        u sJ t	        j
                  t        j                  d|            |z  S )zgCompute portable hash for `key`.

        :param key: key to hash
        :return: hash value

        l    utf-8z!d)puttypesqlite3Binaryzlibadler32strencodeintfloatstructpack)r   keymaskdisk_key_type_disk_keys         r   hashz	Disk.hashv   s     hhsm!XGNN*<<)D00c!<< 89D@@c!d?" E)))<<D( ;<tCCr
   c                 B   t        |      }|t        u rt        j                  |      dfS |t        u s|t
        u rd|cxk  rdk  s
n |t        u r|dfS t        j                  || j                        }t        j                  |      }t        j                  |      dfS )zConvert `key` to fields key and raw for Cache table.

        :param key: key to convert
        :return: (database key, raw boolean) pair

        T             protocolF)rB   bytesrC   rD   rG   rI   rJ   pickledumpsr<   pickletoolsoptimize)r   rM   type_keydataresults        r   rA   zDisk.put   s     9u>>#&,,_C(CF3FFE!9<<d.B.BCD ))$/F>>&)500r
   c                     |r(t        |      t        j                  u rt        |      S |S t	        j
                  t        j                  |            S )zConvert fields `key` and `raw` from Cache table to key.

        :param key: database key to convert
        :param bool raw: flag indicating raw database storage
        :return: corresponding Python key

        )rB   rC   rD   rX   rY   loadioBytesIO)r   rM   raws      r   r4   zDisk.get   s<     !%cgnn!<5:E#E;;rzz#//r
   c                 f   t        |      }| j                  }|t        u rt        |      |k  s|t        u rd|cxk  rdk  s
n |t
        u r
dt        d|fS |t        u ryt        |      |k  rdt        dt        j                  |      fS | j                  ||      \  }}| j                  |t        j                  |      d       t        |      t        |dfS |t        u r[| j                  ||      \  }}| j                  |t        j                  |      dd       t!        j"                  |      }|t$        |dfS |r^t'        j(                  |j*                  d      }	| j                  ||      \  }}t-        |	d	      }
| j                  ||
d      }|t        |dfS t/        j0                  || j2                  
      }t        |      |k  rdt4        dt        j                  |      fS | j                  ||      \  }}| j                  |t        j                  |      d       t        |      t4        |dfS )a:  Convert `value` to fields size, mode, filename, and value for Cache
        table.

        :param value: value to convert
        :param bool read: True when value is file-like object
        :param key: key for item (default UNKNOWN)
        :return: (size, mode, filename, value) tuple for Cache table

        rT   rU   r   NxbxUTF-8i  @ r
   rV   )rB   r;   rG   lenrI   rJ   MODE_RAWrX   rC   rD   filename_writerb   rc   MODE_BINARYStringIOopgetsize	MODE_TEXTftpartialreaditerrY   rZ   r<   MODE_PICKLE)r   valuert   rM   
type_valuer;   rk   	full_pathr0   readeriteratorr_   s               r   storez
Disk.store   s    %[
** 33u:#=c!(EH5HHe#he++5 5zM)(D'..*???&*mmC&?#)Irzz%'8$?5z;$>>3"&--U";HiKK	2;;u#5sGD::i(DHd22ZZ

E2F"&--U";HiFC(H;;y(D9Dh44\\%$2F2FGF6{]*+tW^^F-CCC&*mmC&?#)Irzz&'94@6{K4??r
   Nc                    t        j                  |      \  }}t        dd      D ]  }t        j                  t
              5  t        j                  |       d d d        	 t        |||      }|5  d}	|D ]!  }
|	t        |
      z  }	|j                  |
       # |	cd d d        c S  y # 1 sw Y   RxY w# t
        $ r	 |dk(  r Y w xY w# 1 sw Y   xY w)Nr      encodingr!   r   )ro   splitrangeclsuppressOSErrorosmakedirsopenri   write)r   ry   r{   moder   full_dirrP   r/   writerr0   chunks              r   rl   zDisk._write   s    hhy)!1b\ 	EW% &H%& iA  % (ECJ&DLL'(  	& &  B;	 s*   B( B40*C	(B1	4CC	C	c                 :   |t         k(  r(t        |      t        j                  u rt	        |      S |S |t
        k(  rp|r*t        t        j                  | j                  |      d      S t        t        j                  | j                  |      d      5 }|j                         cddd       S |t        k(  rHt        j                  | j                  |      }t        |dd      5 }|j                         cddd       S |t        k(  rs|It        t        j                  | j                  |      d      5 }t        j                  |      cddd       S t        j                  t        j                   |            S y# 1 sw Y   yxY w# 1 sw Y   yxY w# 1 sw Y   yxY w)a  Convert fields `mode`, `filename`, and `value` from Cache table to
        value.

        :param int mode: value mode raw, binary, text, or pickle
        :param str filename: filename of corresponding value
        :param value: database value
        :param bool read: when True, return an open file handle
        :return: corresponding Python value
        :raises: IOError if the value cannot be read

        rbNrrh   r   )rj   rB   rC   rD   rX   rm   r   ro   joinr:   rt   rq   rv   rY   ra   rb   rc   )r   r   rk   rw   rt   rz   ry   s          r   fetchz
Disk.fetch   sI    8#';'..#@5<KeK[ BGGDOOX>EE"''$//8<dC )v!;;=) )Y:Iiw7 %6{{}% %[ }"''$//8<dC /v!;;v./ / {{2::e#455 !) )% %/ /s$   E9"F1F9FFFc                 .   t        j                  t        j                  d      d      j	                  d      }t        j                  |dd |dd       }|dd dz   }t        j                  ||      }t        j                  | j                  |      }||fS )a  Return filename and full-path tuple for file storage.

        Filename will be a randomly generated 28 character hexadecimal string
        with ".val" suffixed. Two levels of sub-directories will be used to
        reduce the size of directories. On older filesystems, lookups in
        directories with many files may be slow.

        The default implementation ignores the `key` and `value` parameters.

        In some scenarios, for example :meth:`Cache.push
        <diskcache.Cache.push>`, the `key` or `value` may not be known when the
        item is stored in the cache.

        :param key: key for item (default UNKNOWN)
        :param value: value for item (default UNKNOWN)

           hexr@   Nr   r   z.val)codecsrH   r   urandomdecodero   r   r:   )r   rM   rw   hex_namesub_dirr   rk   ry   s           r   rk   zDisk.filename  s    & ==B7>>wG''(2A,16|f$777D)GGDOOX6	""r
   c                    t        j                  | j                  |      }t        j                  |      \  }}t	        j
                  t              5  t        j                  |       ddd       t	        j
                  t              5  t        j                  |       ddd       y# 1 sw Y   AxY w# 1 sw Y   yxY w)zRemove a file given by `file_path`.

        This method is cross-thread and cross-process safe. If an OSError
        occurs, it is suppressed.

        :param str file_path: relative path to file

        N)
ro   r   r:   r   r   r   r   r   remove
removedirs)r   	file_pathry   r   rP   s        r   r   zDisk.remove8  s     GGDOOY7	hhy)!
 [[! 	!IIi 	! [[! 	$MM(#	$ 	$	! 	!	$ 	$s   B(	B4(B14B=)r   r   r   )r   r   r   r   r>   rR   rA   r4   r   r|   rl   r   rk   r   r   r
   r   r8   r8   g   sB    J
/D*140 &- 1@f06@ #' #4$r
   r8   c                   P     e Zd ZdZd fd	Z fdZ fdZef fd	Z fdZ	 xZ
S )JSONDiskzCCache key and value using JSON serialization with zlib compression.c                 4    || _         t        |   |fi | y)a  Initialize JSON disk instance.

        Keys and values are compressed using the zlib library. The
        `compress_level` is an integer from 0 to 9 controlling the level of
        compression; 1 is fastest and produces the least compression, 9 is
        slowest and produces the most compression, and 0 is no compression.

        :param str directory: directory path
        :param int compress_level: zlib compression level (default 1)
        :param kwargs: super class arguments

        N)compress_levelsuperr>   )r   r=   r   kwargs	__class__s       r   r>   zJSONDisk.__init__Q  s     --f-r
   c                     t        j                  |      j                  d      }t        j                  || j
                        }t        |   |      S Nr@   )jsonrZ   rH   rE   compressr   r   rA   )r   rM   
json_bytesr^   r   s       r   rA   zJSONDisk.puta  s@    ZZ_++G4
}}Z)<)<=w{4  r
   c                     t         |   ||      }t        j                  t	        j
                  |      j                  d            S r   )r   r4   r   loadsrE   
decompressr   )r   rM   rd   r^   r   s       r   r4   zJSONDisk.getf  s6    w{3$zz$//$/66w?@@r
   c                     |sDt        j                  |      j                  d      }t        j                  || j
                        }t        |   |||      S )Nr@   rM   )r   rZ   rH   rE   r   r   r   r|   )r   rw   rt   rM   r   r   s        r   r|   zJSONDisk.storej  sJ    E*11':JMM*d.A.ABEw}UDc}22r
   c                     t         |   ||||      }|s7t        j                  t	        j
                  |      j                  d            }|S r   )r   r   r   r   rE   r   r   )r   r   rk   rw   rt   r^   r   s         r   r   zJSONDisk.fetchp  sA    w}T8UD9::dood3::7CDDr
   )r   )r   r   r   r   r>   rA   r4   r   r|   r   __classcell__)r   s   @r   r   r   N  s*    M. !
A &- 3 r
   r   c                       e Zd ZdZy)TimeoutzDatabase timeout expired.Nr   r   r   r   r   r
   r   r   r   w  s    #r
   r   c                       e Zd ZdZy)UnknownFileWarningz.Warning used by Cache.check for unknown files.Nr   r   r
   r   r   r   {  s    8r
   r   c                       e Zd ZdZy)EmptyDirWarningz2Warning used by Cache.check for empty directories.Nr   r   r
   r   r   r     s    <r
   r   c                 X   t        fdt        |      D              }| |z   dz   }|rM|j                         D ci c]  \  }}|vs|| }}}t        |j                               }|D ]  }|z  }	 |r,t        d |D              z  }|r|t        d D              z  }S c c}}w )a=  Create cache key out of function arguments.

    :param tuple base: base of key
    :param tuple args: function arguments
    :param dict kwargs: function keyword arguments
    :param bool typed: include types in cache key
    :param set ignore: positional or keyword args to ignore
    :return: cache key tuple

    c              3   2   K   | ]  \  }}|vs|  y wr   r   ).0indexargignores      r   	<genexpr>zargs_to_key.<locals>.<genexpr>  s     N%v:MNs   r   c              3   2   K   | ]  }t        |        y wr   rB   )r   r   s     r   r   zargs_to_key.<locals>.<genexpr>  s     /3T#Y/s   c              3   8   K   | ]  \  }}t        |        y wr   r   )r   rP   rw   s      r   r   zargs_to_key.<locals>.<genexpr>  s     BEeB   )r   	enumerateitemssorted)	baseargsr   typedr   rM   valsorted_itemsitems	       `    r   args_to_keyr     s     NyNND
+
C+1<<>OxsCS=N#s(OOflln-  	D4KC	 u/$///5B\BBBCJ Ps   B&	B&c                   2   e Zd ZdZddefdZed        Zed        Zed        Z	ed        Z
ed	        Zed
        Zej                  d8d       Zej                  d9d       Zd:dZd Zd Zd Zd;dZd<dZd:dZd=dZd=dZ	 	 	 	 	 d>dZd Zd8dZd Z	 d?dZd@dZd8dZ 	 	 	 	 	 	 dAdZ!	 	 	 	 	 	 dBdZ"	 	 	 	 	 	 dBd Z#dCd!Z$	 dDd"Z%dEd#Z&d$ Z'd% Z(d8d&Z)d<d'Z*d8d(Z+d8d)Z,	 dFd*Z-d8d+Z.d@d,Z/d- Z0d. Z1dGd/Z2d0 Z3d1 Z4d2 Z5d3 Z6d4 Z7d5 Z8d6 Z9e:dfd7Z;y)HCachezDisk and file backed cache.N<   c                 R   	 t        |t              sJ 	 |t        j                  d      }t        |      }t        j                  |      }t        j                  |      }|| _        d| _        t        j                         | _        d| _        t        j"                  |      s	 t%        j&                  |d       | j0                  }	 t3         |d      j5                               }t:        j=                         }|j?                  |       |j?                  |       t@        D ]  }	|jC                  |	d        tE        |jG                               D ]+  \  }	}
|	jI                  d	      s| jK                  |	|
d
       -  |d       |jG                         D 	
ci c]  \  }	}
|	jI                  d      r|	dd |
 }}	}
 ||fi || _&        |jG                         D ]$  \  }	}
d} |||	|
f       | jK                  |	|
       & t@        jG                         D ]#  \  }	}
d} |||	|
f       | jK                  |	       %  |d      j5                         \  \  | _'         |d        |d        |d       tP        | jR                     d   }| ||        |d        |d        |d        |d        |d       | jT                  r| jW                          n| jY                          | j[                          || _        | j\                   y# t        t        f$ r t	        d      dw xY w# t(        $ rL}|j*                  t*        j,                  k7  r$t/        |j*                  d| j                  z        dY d}~d}~ww xY w# t6        j8                  $ r i }Y w xY wc c}
}	w )zInitialize cache instance.

        :param str directory: cache directory
        :param float timeout: SQLite connection timeout
        :param disk: Disk type or subclass for serialization
        :param settings: any of DEFAULT_SETTINGS

        z!disk must subclass diskcache.DiskNz
diskcache-)prefixr   i  z<Cache directory "%s" does not exist and could not be createdSELECT key, value FROM Settingssqlite_FupdatezFCREATE TABLE IF NOT EXISTS Settings ( key TEXT NOT NULL UNIQUE, value)disk_   z-INSERT OR REPLACE INTO Settings VALUES (?, ?)z,INSERT OR IGNORE INTO Settings VALUES (?, ?)zPRAGMA page_sizezCREATE TABLE IF NOT EXISTS Cache ( rowid INTEGER PRIMARY KEY, key BLOB, raw INTEGER, store_time REAL, expire_time REAL, access_time REAL, access_count INTEGER DEFAULT 0, tag BLOB, size INTEGER DEFAULT 0, mode INTEGER DEFAULT 0, filename TEXT, value BLOB)zBCREATE UNIQUE INDEX IF NOT EXISTS Cache_key_raw ON Cache(key, raw)zCCREATE INDEX IF NOT EXISTS Cache_expire_time ON Cache (expire_time)r3   zCREATE TRIGGER IF NOT EXISTS Settings_count_insert AFTER INSERT ON Cache FOR EACH ROW BEGIN UPDATE Settings SET value = value + 1 WHERE key = "count"; ENDzCREATE TRIGGER IF NOT EXISTS Settings_count_delete AFTER DELETE ON Cache FOR EACH ROW BEGIN UPDATE Settings SET value = value - 1 WHERE key = "count"; ENDzCREATE TRIGGER IF NOT EXISTS Settings_size_insert AFTER INSERT ON Cache FOR EACH ROW BEGIN UPDATE Settings SET value = value + NEW.size WHERE key = "size"; ENDzCREATE TRIGGER IF NOT EXISTS Settings_size_update AFTER UPDATE ON Cache FOR EACH ROW BEGIN UPDATE Settings SET value = value + NEW.size - OLD.size WHERE key = "size"; ENDzCREATE TRIGGER IF NOT EXISTS Settings_size_delete AFTER DELETE ON Cache FOR EACH ROW BEGIN UPDATE Settings SET value = value - OLD.size WHERE key = "size"; END)/
issubclassr8   	TypeErrorAssertionError
ValueErrortempfilemkdtemprG   ro   
expanduser
expandvarsr:   _timeout	threadinglocal_local_txn_idisdirr   r   r   errnoEEXISTEnvironmentError
_sql_retrydictfetchallrC   OperationalErrorDEFAULT_SETTINGScopyr   METADATApopr   r   
startswithreset_disk
_page_sizeEVICTION_POLICYr%   r$   create_tag_indexdrop_tag_indexclose_sql)r   r=   timeoutdisksettingserrorsqlcurrent_settingssetsrM   rw   r   querys                r   r>   zCache.__init__  s   	LdD)))  ((=I	N	MM),	MM),	#oo'xx	" Iu- oo	"#56??A   $$&$%H 	 CHHS$	 
 !. 	5JC~~i(

3e
4	5 		
 #jjl
U~~g& GUN
 

 ).v.
 **, 	#JCCEU|$JJsE"	#
 #..* 	JCBEU|$JJsO	
 !$$6 7 @ @ B	$/ 		
  		

 	#	

   4 45f=J 	(	
 	(	
 	'	
 	'	
 	'	
 >>!!#! 	

		A >* 	L@AtK	L"   ;;%,,.*46:ooF  	  /   '' 	"!	"0
s<   L &L/ 	N !N#L,/	N8AM??NN N c                     | j                   S )zCache directory.)r:   r   s    r   r=   zCache.directoryQ  s     r
   c                     | j                   S )z+SQLite connection timeout value in seconds.)r   r   s    r   r   zCache.timeoutV  s     }}r
   c                     | j                   S )zDisk used for serialization.)r   r   s    r   r   z
Cache.disk[  s     zzr
   c                 `   t        | j                  dd       }t        j                         }||k7  r!| j	                          || j                  _        t        | j                  dd       }|t        j                  t        j                  | j                  t              | j                  d       x}| j                  _        	 d}|j                  |      j                         }|D ]+  \  }}|j!                  d      s| j#                  ||d       - |S |S # t        j$                  $ r Y |S w xY w)Npidcon)r   isolation_levelr   r   Fr   )getattrr   r   getpidr   r  rC   connectro   r   r:   DBNAMEr   r  executer   r   r   r   )r   	local_pidr  r  selectr   rM   rw   s           r   _conz
Cache._con`  s   
 DKK5	iikJJL!DKKOdkk5$/;$+OO0 $% C$++/=:;;v.779 #+ =JC~~i0

3e
<= 
s
 ++  
s   !D D-,D-c                 .    | j                   j                  S r   )r  r  r   s    r   r   z
Cache._sql  s    yy   r
   c                 *    | j                   fd}|S )Nc                    t        j                          }	 	  | g|i |S # t        j                  $ rK}t        |      dk7  r t        j                          |z
  }|dkD  r t        j                  d       Y d }~nd }~ww xY wo)Ndatabase is lockedr   MbP?)timerC   r   rG   sleep)	statementr   r   startexcdiffr   s         r   _execute_with_retryz-Cache._sql_retry.<locals>._execute_with_retry  s    IIKE&y:4:6::// &3x#7799;.DbyJJu%%& s   $ BAA==Br   )r   r  r   s     @r   r   zCache._sql_retry  s    ii	& #"r
   c              #   b   K   | j                  |      5  d ddd       y# 1 sw Y   yxY ww)a+  Context manager to perform a transaction by locking the cache.

        While the cache is locked, no other write operation is permitted.
        Transactions should therefore be as short as possible. Read and write
        operations performed in a transaction are atomic. Read operations may
        occur concurrent to a transaction.

        Transactions may be nested and may not be shared between threads.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        >>> cache = Cache()
        >>> with cache.transact():  # Atomically increment two keys.
        ...     _ = cache.incr('total', 123.4)
        ...     _ = cache.incr('count', 1)
        >>> with cache.transact():  # Atomically calculate average.
        ...     average = cache['total'] / cache['count']
        >>> average
        123.4

        :param bool retry: retry if database timeout occurs (default False)
        :return: context manager for use in `with` statement
        :raises Timeout: if database timeout occurs

        retryN)	_transact)r   r!  s     r   transactzCache.transact  s-     8 ^^%^( 		 	 	s   /#	/,/c              #     K   | j                   }g }| j                  j                  }t        j                         }| j
                  }||k(  rd}n	 	  |d       d}|| _        	 	 ||j                  f |r | j
                  |k(  sJ d | _         |d       |D ]  }	|	 ||	        y # t        j                  $ r |rY q| ||       t        d w xY w# t        $ r$ |r | j
                  |k(  sJ d | _         |d        w xY ww)NFTzBEGIN IMMEDIATECOMMITROLLBACK)r   r   r   r   	get_identr   rC   r   r   appendBaseException)
r   r!  rk   r   	filenames_disk_removetidtxn_idbeginr   s
             r   r"  zCache._transact  s&    ii	zz((!!#&=E
,)* E#&DL	'y'''' ||s***#H! '# &') // , +$X.!t+,  	||s***#J	sH   ADB) "D$C 4)DD)C>D CD-DDc                    t        j                          }| j                  j                  |      \  }}	|dn||z   }
| j                  j                  |||      \  }}}}|
|||||f}| j	                  ||      5 \  }} |d||	f      j                         }|r#|\  \  }} ||       | j                  |||       n| j                  ||	||       | j                  |||       	 ddd       y# 1 sw Y   yxY w)a  Set `key` and `value` item in cache.

        When `read` is `True`, `value` should be a file-like object opened
        for reading in binary mode.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param value: value for item
        :param float expire: seconds until item expires
            (default None, no expiry)
        :param bool read: read value as bytes from file (default False)
        :param str tag: text to associate with key (default None)
        :param bool retry: retry if database timeout occurs (default False)
        :return: True if item was set
        :raises Timeout: if database timeout occurs

        Nr   z;SELECT rowid, filename FROM Cache WHERE key = ? AND raw = ?T	r  r   rA   r|   r"  r   _row_update_row_insert_cull)r   rM   rw   expirert   tagr!  nowdb_keyrd   expire_timer0   r   rk   db_valuecolumnsr   cleanuprowsrowidold_filenames                        r   setz	Cache.set  s
   ( iikjjnnS)$nd#,)-)9)9%3)9)O&dHhT48D. ^^E8, 	g- hj	  +/(&%%  W5  c7;JJsC)!	 	 	s   9A*C,,C5c                 ,    | j                  ||d       y)zSet corresponding `value` for `key` in cache.

        :param key: key for item
        :param value: value for item
        :return: corresponding value
        :raises KeyError: if key is not found

        Tr   N)r?  r   rM   rw   s      r   __setitem__zCache.__setitem__.  s     	e4(r
   c                 T    | j                   }|\  }}}}}	}
 |d|||d||||	|
|f
       y )NzUPDATE Cache SET store_time = ?, expire_time = ?, access_time = ?, access_count = ?, tag = ?, size = ?, mode = ?, filename = ?, value = ? WHERE rowid = ?r   r  )r   r=  r6  r:  r   r8  r5  r0   r   rk   rw   s              r   r1  zCache._row_update9  sO    ii8?5S$h
 	
r
   c                 V    | j                   }|\  }}}}	}
} |d|||||d|||	|
|f       y )NzINSERT INTO Cache( key, raw, store_time, expire_time, access_time, access_count, tag, size, mode, filename, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)r   r  )r   rM   rd   r6  r:  r   r8  r5  r0   r   rk   rw   s               r   r2  zCache._row_insertV  sR    ii8?5S$h9
 	
r
   c                    || j                   n|}|dk(  ry d}|dz  } ||||f      j                         }|r8d|dz  z  }	 ||	||f       |D ]  \  }
 ||
        |t        |      z  }|dk(  ry t        | j                     d   }|| j                         | j                  k  ry |j                  d|      } |||f      j                         }|r2d|j                  d|      z  } |||f       |D ]  \  }
 ||
        y y )Nr   zcSELECT %s FROM Cache WHERE expire_time IS NOT NULL AND expire_time < ? ORDER BY expire_time LIMIT ?rk   %DELETE FROM Cache WHERE rowid IN (%s)r=  r5   fieldsr6  )r'   r   ri   r   r%   volumer&   format)r   r6  r   r;  limitr'   select_expired_templateselect_expiredr<  delete_expiredrk   select_policyselect_filenamedeletes                 r   r3  zCache._cullm  sM   (-T__5
?
, 	  1:=>C#45>>@D''1N j 12# "!" #d)#JQ ((<(<=fE DKKMDOO$C'..jc.J?ZM2;;=<$$G$=F &# "!" r
   c                 H   t        j                          }| j                  j                  |      \  }}|dn||z   }| j                  |      5 \  }}	 |d||f      j	                         }
|
r#|
\  \  }}|||kD  r |d||f       	 ddd       yddd       y# 1 sw Y   yxY w)a  Touch `key` in cache and update `expire` time.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param float expire: seconds until item expires
            (default None, no expiry)
        :param bool retry: retry if database timeout occurs (default False)
        :return: True if key was touched
        :raises Timeout: if database timeout occurs

        Nz>SELECT rowid, expire_time FROM Cache WHERE key = ? AND raw = ?z0UPDATE Cache SET expire_time = ? WHERE rowid = ?TF)r  r   rA   r"  r   )r   rM   r4  r!  r6  r7  rd   r8  r   rP   r<  r=  old_expire_times                r   touchzCache.touch  s     iikjjnnS)$nd#,^^E" 	 hsA- hj	  .2+)%"*o.CJ$e,  	  	  	 " #	 " s   9BB!c                 $   t        j                          }| j                  j                  |      \  }}	|dn||z   }
| j                  j                  |||      \  }}}}|
|||||f}| j	                  ||      5 \  }} |d||	f      j                         }|r=|\  \  }}}|||kD  r ||       	 ddd       y ||       | j                  |||       n| j                  ||	||       | j                  |||       	 ddd       y# 1 sw Y   yxY w)a  Add `key` and `value` item to cache.

        Similar to `set`, but only add to cache if key not present.

        Operation is atomic. Only one concurrent add operation for a given key
        will succeed.

        When `read` is `True`, `value` should be a file-like object opened
        for reading in binary mode.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param value: value for item
        :param float expire: seconds until the key expires
            (default None, no expiry)
        :param bool read: read value as bytes from file (default False)
        :param str tag: text to associate with key (default None)
        :param bool retry: retry if database timeout occurs (default False)
        :return: True if item was added
        :raises Timeout: if database timeout occurs

        Nr   zHSELECT rowid, filename, expire_time FROM Cache WHERE key = ? AND raw = ?FTr0  )r   rM   rw   r4  rt   r5  r!  r6  r7  rd   r8  r0   r   rk   r9  r:  r   r;  r<  r=  r>  rS  s                         r   addz	Cache.add  s.   2 iikjjnnS)$nd#,)-)9)9%3)9)O&dHhT48D^^E8, 	g- hj	  <@97%"*o.CH% 	 	 %  W5  c7;JJsC)+	 	 	s   97D9ADDc                 J   t        j                          }| j                  j                  |      \  }}d}| j                  |      5 \  }	}
 |	|||f      j	                         }|se|t        |      ||z   }d| j                  j                  |d|      z   }| j                  ||||       | j                  ||	|
       |cddd       S |\  \  }}}}|q||k  rl|t        |      ||z   }d| j                  j                  |d|      z   }| j                  |||       | j                  ||	|
        |
|       |cddd       S ||z  }d}t        | j                     d   }||d|j                  |	      z   z  }d
|z  } |	||||f       |cddd       S # 1 sw Y   yxY w)a  Increment value by delta for item with key.

        If key is missing and default is None then raise KeyError. Else if key
        is missing and default is not None then use default for value.

        Operation is atomic. All concurrent increment operations will be
        counted individually.

        Assumes value may be stored in a SQLite column. Most builds that target
        machines with 64-bit pointer widths will support 64-bit signed
        integers.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param int delta: amount to increment (default 1)
        :param int default: value if key is missing (default 0)
        :param bool retry: retry if database timeout occurs (default False)
        :return: new value for item
        :raises KeyError: if key is not found and default is None
        :raises Timeout: if database timeout occurs

        zOSELECT rowid, expire_time, filename, value FROM Cache WHERE key = ? AND raw = ?NNNFr   zstore_time = ?, value = ?r4   z, r6  #UPDATE Cache SET %s WHERE rowid = ?)r  r   rA   r"  r   KeyErrorr|   r2  r3  r1  r   r%   rJ  )r   rM   deltadefaultr!  r6  r7  rd   r  r   r;  r<  rw   r:  r=  r8  rk   update_columnr   s                      r   incrz
Cache.incr  s   2 iikjjnnS)) 	
 ^^E" )	nsGv}-668D?"3-'%&)9)95c *: *    c7;

3W-)	 )	 8<42e[(E&;+<?"3-'%&)9)95c *: *    W5

3W-!9)	 )	< UNE1G+D,@,@A%HM(4-"6"63"6"???:WDFeU+,S)	 )	 )	s   A:F
A2FA	FF"c                 ,    | j                  || ||      S )a3  Decrement value by delta for item with key.

        If key is missing and default is None then raise KeyError. Else if key
        is missing and default is not None then use default for value.

        Operation is atomic. All concurrent decrement operations will be
        counted individually.

        Unlike Memcached, negative values are supported. Value may be
        decremented below zero.

        Assumes value may be stored in a SQLite column. Most builds that target
        machines with 64-bit pointer widths will support 64-bit signed
        integers.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param int delta: amount to decrement (default 1)
        :param int default: value if key is missing (default 0)
        :param bool retry: retry if database timeout occurs (default False)
        :return: new value for item
        :raises KeyError: if key is not found and default is None
        :raises Timeout: if database timeout occurs

        )r_  )r   rM   r\  r]  r!  s        r   decrz
Cache.decrE  s    8 yyufgu55r
   c                    | j                   j                  |      \  }}t        | j                     d   }	d}
|r|r|ddf}n|s|r|df}| j                  sf|	d| j                  |
||t        j                         f      j                         }|s|S |\  \  }}}}}}	 | j                   j                  ||||      }nd}d}| j                  |      5 \  }} ||
||t        j                         f      j                         }|s| j                  r ||       |cddd       S |\  \  }}}}}}	 | j                   j                  ||||      }| j                  r ||       t        j                         }d}|	 |||	j                  |      z  |f       ddd       |r|rfS |rfS |rfS S # t        $ r |cY S w xY w# t        $ r" | j                  r ||       |cY cddd       S w xY w# 1 sw Y   _xY w)a  Retrieve value from cache. If `key` is missing, return `default`.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param default: value to return if key is missing (default None)
        :param bool read: if True, return file handle to value
            (default False)
        :param bool expire_time: if True, return expire_time in tuple
            (default False)
        :param bool tag: if True, return tag in tuple (default False)
        :param bool retry: retry if database timeout occurs (default False)
        :return: value for item or default if key not found
        :raises Timeout: if database timeout occurs

        r4   SELECT rowid, expire_time, tag, mode, filename, value FROM Cache WHERE key = ? AND raw = ? AND (expire_time IS NULL OR expire_time > ?)Nz8UPDATE Settings SET value = value + 1 WHERE key = "hits"z:UPDATE Settings SET value = value + 1 WHERE key = "misses"rZ  rY  )r   rA   r   r%   r#   r   r  r   r   IOErrorr"  rJ  )r   rM   r]  rt   r8  r5  r!  r7  rd   r^  r  r<  r=  db_expire_timedb_tagr   rk   r9  rw   	cache_hit
cache_missr   rP   r6  r   s                            r   r4   z	Cache.getc  sF   4 jjnnS)'(<(<=eD< 	 3d+GCoG=#8 99Vfc499;%?@IIKDKOHFe^VT8X

((x4H K  M  & J(36FC#=>GGIJ"J J MUNFD(H# JJ,,T8XtLE ??	Niik> ,!5!5#!5!>>I7J: 3>622>**6?"La  4  #J"N%J J#J JsJ   F3 AG2!G2-GA	G23G GG/#G2.G//G22G;c                 \    | j                  |t        d      }|t        u rt        |      |S )zReturn corresponding value for `key` from cache.

        :param key: key matching item
        :return: corresponding value
        :raises KeyError: if key is not found

        Tr]  r!  r4   r   r[  rA  s      r   __getitem__zCache.__getitem__  s.     fD9F?3-r
   c                 ^    | j                  |t        d|      }|t        u rt        |      |S )a  Return file handle value corresponding to `key` from cache.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key matching item
        :param bool retry: retry if database timeout occurs (default False)
        :return: file open for reading in binary mode
        :raises KeyError: if key is not found
        :raises Timeout: if database timeout occurs

        T)r]  rt   r!  rk  )r   rM   r!  handles       r   rt   z
Cache.read  s1     #vDFV3-r
   c                     | j                   }| j                  j                  |      \  }}d} ||||t        j                         f      j	                         }t        |      S )zReturn `True` if `key` matching item is found in cache.

        :param key: key matching item
        :return: True if key matching item

        z^SELECT rowid FROM Cache WHERE key = ? AND raw = ? AND (expire_time IS NULL OR expire_time > ?))r   r   rA   r  r   bool)r   rM   r   r7  rd   r  r<  s          r   __contains__zCache.__contains__  s[     iijjnnS)< 	 6FC56??ADzr
   c                    | j                   j                  |      \  }}d}|r|r|ddf}n|s|r|df}| j                  |      5 \  }	}
 |	|||t        j                         f      j	                         }|s|cddd       S |\  \  }}}}}} |	d|f       ddd       	 | j                   j                  d      }	 || j                   j                  |       	 |r|r|fS |r|fS |r|fS |S # 1 sw Y   ^xY w# t        $ r# |cY | j                   j                  |       S S w xY w# | j                   j                  |       w w xY w)a  Remove corresponding item for `key` from cache and return value.

        If `key` is missing, return `default`.

        Operation is atomic. Concurrent operations will be serialized.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key for item
        :param default: value to return if key is missing (default None)
        :param bool expire_time: if True, return expire_time in tuple
            (default False)
        :param bool tag: if True, return tag in tuple (default False)
        :param bool retry: retry if database timeout occurs (default False)
        :return: value for item or default if key not found
        :raises Timeout: if database timeout occurs

        rc  N!DELETE FROM Cache WHERE rowid = ?F)r   rA   r"  r  r   r   rd  r   )r   rM   r]  r8  r5  r!  r7  rd   r  r   rP   r<  r=  re  rf  r   rk   r9  rw   s                      r   r   z	Cache.pop  s   , jjnnS)< 	 3tT)GCtmG^^E" 	?hsAvTYY[9:CCED		? 	? LPHFe^VT8X3eX>	?	,JJ$$T8XuEE
 #

!!(+3.&00.((&= L5	? 	?  	N#

!!(+ $		 #

!!(+ $s6   3C3C3C? 3C<?D+
D. *D++D. . ETc                 8   | j                   j                  |      \  }}| j                  |      5 \  }} |d||t        j                         f      j	                         }|st        |      |\  \  }}	 |d|f        ||	       	 ddd       y# 1 sw Y   yxY w)a  Delete corresponding item for `key` from cache.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default `True`).

        :param key: key matching item
        :param bool retry: retry if database timeout occurs (default True)
        :raises KeyError: if key is not found
        :raises Timeout: if database timeout occurs

        zhSELECT rowid, filename FROM Cache WHERE key = ? AND raw = ? AND (expire_time IS NULL OR expire_time > ?)rs  NT)r   rA   r"  r  r   r[  )
r   rM   r!  r7  rd   r   r;  r<  r=  rk   s
             r   __delitem__zCache.__delitem__8  s     jjnnS)^^E" 	nsG@ diik*	
 hj  sm##' eX3eX>H	 	 	s   ABBc                 H    	 | j                  ||      S # t        $ r Y yw xY w)a  Delete corresponding item for `key` from cache.

        Missing keys are ignored.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param key: key matching item
        :param bool retry: retry if database timeout occurs (default False)
        :return: True if item was deleted
        :raises Timeout: if database timeout occurs

        r   F)ru  r[  )r   rM   r!  s      r   rQ  zCache.deleteW  s/    	##Cu#55 		s    	!!c                 f   |d}d}	n
|dz   }|dz   }	t        j                          }
d}|dn|
|z   }| j                  j                  ||      \  }}}}||||||f}ddd	}d
||   z  }| j                  ||      5 \  }} ||||	|f      j	                         }|rC|\  \  }|!t        ||j                  d      dz   d       }n|}|dk(  r|dz  }n|dk(  sJ |dz  }nd}|dj                  ||      }n|}| j                  |||
|       | j                  |
||       |cddd       S # 1 sw Y   yxY w)a  Push `value` onto `side` of queue identified by `prefix` in cache.

        When prefix is None, integer keys are used. Otherwise, string keys are
        used in the format "prefix-integer". Integer starts at 500 trillion.

        Defaults to pushing value on back of queue. Set side to 'front' to push
        value on front of queue. Side must be one of 'back' or 'front'.

        Operation is atomic. Concurrent operations will be serialized.

        When `read` is `True`, `value` should be a file-like object opened
        for reading in binary mode.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        See also `Cache.pull`.

        >>> cache = Cache()
        >>> print(cache.push('first value'))
        500000000000000
        >>> cache.get(500000000000000)
        'first value'
        >>> print(cache.push('second value'))
        500000000000001
        >>> print(cache.push('third value', side='front'))
        499999999999999
        >>> cache.push(1234, prefix='userids')
        'userids-500000000000000'

        :param value: value for item
        :param str prefix: key prefix (default None, key is integer)
        :param str side: either 'back' or 'front' (default 'back')
        :param float expire: seconds until the key expires
            (default None, no expiry)
        :param bool read: read value as bytes from file (default False)
        :param str tag: text to associate with key (default None)
        :param bool retry: retry if database timeout occurs (default False)
        :return: key for item in cache
        :raises Timeout: if database timeout occurs

        Nr      I5 -000000000000000-999999999999999TDESCASC)backfrontzSSELECT key FROM Cache WHERE ? < key AND key < ? AND raw = ? ORDER BY key %s LIMIT 1-r   r}  r~  l    @$ z{0}-{1:015d})
r  r   r|   r"  r   rI   rfindrJ  r2  r3  )r   rw   r   sider4  rt   r5  r!  min_keymax_keyr6  rd   r8  r0   r   rk   r9  r:  orderr  r   r;  r<  rM   numr7  s                             r   pushz
Cache.pushk  s   h >G%G11G11Giik$nd#,)-)9)9%)F&dHhT48D%0' $K	 ^^E8, 	gv#67@@BD 	#%c399S>A#5"89:CC6>1HC7?*?1HC%!'..vs;VS#w7JJsC)7	 	 	s   9B$D''D0c                    |d}d}n
|dz   }|dz   }ddd}	d	|	|   z  }
|r|r|ddf}n|s|r|df}	 	 | j                  |      5 \  }} ||
||f      j                         }|s|cddd       S |\  \  }}}}}}} |d
|f       | |t        j                         k  r	 ||       n
	 ddd       n
	 ddd       	 | j                  j	                  |||d      }	 || j                  j                  |       	 	 |r	|r||f||fS |r||f|fS |r||f|fS ||fS # 1 sw Y   hxY w# t
        $ r# Y || j                  j                  |       w xY w# || j                  j                  |       w w xY w)a,  Pull key and value item pair from `side` of queue in cache.

        When prefix is None, integer keys are used. Otherwise, string keys are
        used in the format "prefix-integer". Integer starts at 500 trillion.

        If queue is empty, return default.

        Defaults to pulling key and value item pairs from front of queue. Set
        side to 'back' to pull from back of queue. Side must be one of 'front'
        or 'back'.

        Operation is atomic. Concurrent operations will be serialized.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        See also `Cache.push` and `Cache.get`.

        >>> cache = Cache()
        >>> cache.pull()
        (None, None)
        >>> for letter in 'abc':
        ...     print(cache.push(letter))
        500000000000000
        500000000000001
        500000000000002
        >>> key, value = cache.pull()
        >>> print(key)
        500000000000000
        >>> value
        'a'
        >>> _, value = cache.pull(side='back')
        >>> value
        'c'
        >>> cache.push(1234, 'userids')
        'userids-500000000000000'
        >>> _, value = cache.pull('userids')
        >>> value
        1234

        :param str prefix: key prefix (default None, key is integer)
        :param default: value to return if key is missing
            (default (None, None))
        :param str side: either 'front' or 'back' (default 'front')
        :param bool expire_time: if True, return expire_time in tuple
            (default False)
        :param bool tag: if True, return tag in tuple (default False)
        :param bool retry: retry if database timeout occurs (default False)
        :return: key and value item pair or default if queue is empty
        :raises Timeout: if database timeout occurs

        Nr   rx  ry  rz  r|  r{  r~  r}  SELECT rowid, key, expire_time, tag, mode, filename, value FROM Cache WHERE ? < key AND key < ? AND raw = 1 ORDER BY key %s LIMIT 1rs  F)r"  r   r  r   r   rd  r   r   r   r]  r  r8  r5  r!  r  r  r  r  r   r;  r<  r=  rM   	db_expirerf  r   r   r9  rw   s                         r   pullz
Cache.pull  s   | >G%G11G11G0' $K	 3tT)GCtmG^^E* nsGv'9:CCED&	  MYdH ;eXF ,TYY[1H  & $,

((tXuE
 #JJ%%d+3<F22<**<'':E &  #JJ%%d+ #JJ%%d+ $s6    D.9D;D$ D!$	E-E EE  E3c                 (   |d}d}n
|dz   }|dz   }ddd}	d	|	|   z  }
|r|r|ddf}n|s|r|df}	 	 | j                  |      5 \  }} ||
||f      j                         }|s|cddd       S |\  \  }}}}}}}|*|t        j                         k  r |d
|f        ||       n
	 ddd       n
	 ddd       	 | j                  j	                  |||d      }	 |r	|r||f||fS |r||f|fS |r||f|fS ||fS # 1 sw Y   IxY w# t
        $ r Y w xY w)a  Peek at key and value item pair from `side` of queue in cache.

        When prefix is None, integer keys are used. Otherwise, string keys are
        used in the format "prefix-integer". Integer starts at 500 trillion.

        If queue is empty, return default.

        Defaults to peeking at key and value item pairs from front of queue.
        Set side to 'back' to pull from back of queue. Side must be one of
        'front' or 'back'.

        Expired items are deleted from cache. Operation is atomic. Concurrent
        operations will be serialized.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        See also `Cache.pull` and `Cache.push`.

        >>> cache = Cache()
        >>> for letter in 'abc':
        ...     print(cache.push(letter))
        500000000000000
        500000000000001
        500000000000002
        >>> key, value = cache.peek()
        >>> print(key)
        500000000000000
        >>> value
        'a'
        >>> key, value = cache.peek(side='back')
        >>> print(key)
        500000000000002
        >>> value
        'c'

        :param str prefix: key prefix (default None, key is integer)
        :param default: value to return if key is missing
            (default (None, None))
        :param str side: either 'front' or 'back' (default 'front')
        :param bool expire_time: if True, return expire_time in tuple
            (default False)
        :param bool tag: if True, return tag in tuple (default False)
        :param bool retry: retry if database timeout occurs (default False)
        :return: key and value item pair or default if queue is empty
        :raises Timeout: if database timeout occurs

        Nr   rx  ry  rz  r|  r{  r  r  rs  F)r"  r   r  r   r   rd  r  s                         r   peekz
Cache.peekF  s   t >G%G11G11G0' $K	 3tT)GCtmG^^E* nsGv'9:CCED&	  MYdH !,TYY[1H?%J  & "

((tXuE 3<F22<**<'':= $  s$    C9.9C9;D 9D	DDc           	         d}d||   z  }	 	 | j                  |      5 \  }} ||      j                         }	|	st        d      |	\  \  }
}}}}}}}|*|t        j                         k  r |d|
f        ||       n
	 ddd       n
	 ddd       | j                  j                  ||      }	 | j                  j                  |||d      }	 |r	|r||f||fS |r||f|fS |r||f|fS ||fS # 1 sw Y   exY w# t        $ r Y w xY w)a  Peek at key and value item pair in cache based on iteration order.

        Expired items are deleted from cache. Operation is atomic. Concurrent
        operations will be serialized.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        >>> cache = Cache()
        >>> for num, letter in enumerate('abc'):
        ...     cache[letter] = num
        >>> cache.peekitem()
        ('c', 2)
        >>> cache.peekitem(last=False)
        ('a', 0)

        :param bool last: last item in iteration order (default True)
        :param bool expire_time: if True, return expire_time in tuple
            (default False)
        :param bool tag: if True, return tag in tuple (default False)
        :param bool retry: retry if database timeout occurs (default False)
        :return: key and value item pair
        :raises KeyError: if cache is empty
        :raises Timeout: if database timeout occurs

        )r|  r{  zdSELECT rowid, key, raw, expire_time, tag, mode, filename, value FROM Cache ORDER BY rowid %s LIMIT 1zdictionary is emptyNrs  F)r"  r   r[  r  r   r4   r   rd  )r   lastr8  r5  r!  r  r  r   r;  r<  r=  r7  rd   r  rf  r   r   r9  rM   rw   s                       r   peekitemzCache.peekitem  se   6  4$K
 ^^E* nsGv;//1D&'<== 	!"%"  $ !,TYY[1H?%J/ * &+ 4 **..-C

((tXuE 3<F22<**<'':S :  s   A!C-/C9 -C69	DDc                 R     t              rt        d       fd}|S )a	  Memoizing cache decorator.

        Decorator to wrap callable with memoizing function using cache.
        Repeated calls with the same arguments will lookup result in cache and
        avoid function evaluation.

        If name is set to None (default), the callable name will be determined
        automatically.

        When expire is set to zero, function results will not be set in the
        cache. Cache lookups still occur, however. Read
        :doc:`case-study-landing-page-caching` for example usage.

        If typed is set to True, function arguments of different types will be
        cached separately. For example, f(3) and f(3.0) will be treated as
        distinct calls with distinct results.

        The original underlying function is accessible through the __wrapped__
        attribute. This is useful for introspection, for bypassing the cache,
        or for rewrapping the function with a different cache.

        >>> from diskcache import Cache
        >>> cache = Cache()
        >>> @cache.memoize(expire=1, tag='fib')
        ... def fibonacci(number):
        ...     if number == 0:
        ...         return 0
        ...     elif number == 1:
        ...         return 1
        ...     else:
        ...         return fibonacci(number - 1) + fibonacci(number - 2)
        >>> print(fibonacci(100))
        354224848179261915075

        An additional `__cache_key__` attribute can be used to generate the
        cache key used for the given arguments.

        >>> key = fibonacci.__cache_key__(100)
        >>> print(cache[key])
        354224848179261915075

        Remember to call memoize when decorating a callable. If you forget,
        then a TypeError will occur. Note the lack of parenthenses after
        memoize below:

        >>> @cache.memoize
        ... def test():
        ...     pass
        Traceback (most recent call last):
            ...
        TypeError: name cannot be callable

        :param cache: cache to store callable arguments and return values
        :param str name: name given for callable (default None, automatic)
        :param bool typed: cache different types separately (default False)
        :param float expire: seconds until arguments expire
            (default None, no expiry)
        :param str tag: text to associate with arguments (default None)
        :param set ignore: positional or keyword args to ignore (default ())
        :return: callable decorator

        zname cannot be callablec                      t               fnft        j                          fd       	fd}|_        S )z3Decorator created by memoize() for callable `func`.c                       j                   | i |}j                  |t        d      }|t        u r% | i |}dkD  rj                  ||d       |S )z:Wrapper for callable to cache arguments and return values.Trj  r   )r5  r!  )__cache_key__r4   r   r?  )	r   r   rM   r_   r4  r   r   r5  wrappers	       r   r  z1Cache.memoize.<locals>.decorator.<locals>.wrapperL  sm     ,g++T<V<#vTBV#!4262F~!ff#TJr
   c                  "    t        | |      S )z,Make key for cache given function arguments.)r   )r   r   r   r   r   s     r   r  z7Cache.memoize.<locals>.decorator.<locals>.__cache_key__Y  s    "4vufEEr
   )r	   rr   wrapsr  )
r   r  r   r  r4  r   r   r   r5  r   s
   ` @@r   	decoratorz Cache.memoize.<locals>.decoratorH  sF    )-IdO%D7DXXd^
 
F %2G!Nr
   )callabler   )r   r   r   r4  r5  r   r  s   `````` r   memoizezCache.memoize  s+    D D>566	 	0 r
   c           
          t        j                  d      5 }| j                  } |d      j                         }t	        |      dk7  s|d   d   dk7  r|D ]  \  }t        j
                  |        |r |d       | j                  |      5 \  }}t               }d}	 ||	      j                         }|D ]  \  }
}}t        j                  | j                  |      }|j                  |       t        j                  |      rGt        j                  |      }||k7  r,d	}|||f}t        j
                  ||z         |r |d
||
f       t        j
                  d|z         |s |d|
f        t        j                  | j                        D ]~  \  }}}|D cg c]  }t        j                  ||       }}t        |      |z
  }|D ]B  }t         |v rd|z  }t        j
                  |t"               |s.t        j$                  |       D  t        j                  | j                        D ]C  \  }}}|r
|rd|z  }t        j
                  |t&               |s/t        j(                  |       E | j+                  d        |d      j                         \  \  }| j,                  |k7  r3d}t        j
                  || j,                  |fz         |r |d|df       | j+                  d       d} ||      j                         \  \  }| j.                  |k7  r3d}t        j
                  || j.                  |fz         |r |d|df       ddd       |cddd       S c c}w # 1 sw Y   xY w# 1 sw Y   yxY w)a,  Check database and file system consistency.

        Intended for use in testing and post-mortem error analysis.

        While checking the Cache table for consistency, a writer lock is held
        on the database. The lock blocks other cache clients from writing to
        the database. For caches with many file references, the lock may be
        held for a long time. For example, local benchmarking shows that a
        cache with 1,000 file references takes ~60ms to check.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param bool fix: correct inconsistencies
        :param bool retry: retry if database timeout occurs (default False)
        :return: list of warnings
        :raises Timeout: if database timeout occurs

        T)recordzPRAGMA integrity_checkr   r   okVACUUMzBSELECT rowid, size, filename FROM Cache WHERE filename IS NOT NULLzwrong file size: %s, %d != %dz)UPDATE Cache SET size = ? WHERE rowid = ?zfile not found: %srs  zunknown file: %szempty directory: %sr/   zSELECT COUNT(key) FROM Cachez,Settings.count != COUNT(Cache.key); %d != %d+UPDATE Settings SET value = ? WHERE key = ?r0   z(SELECT COALESCE(SUM(size), 0) FROM Cachez*Settings.size != SUM(Cache.size); %d != %dz*UPDATE Settings SET value = ? WHERE key =?N)warningscatch_warningsr   r   ri   warnr"  r?  ro   r   r:   rV  existsrp   r   walkr  r   r   r   rmdirr   r/   r0   )r   fixr!  warnsr   r<  messagerP   r*  r  r=  r0   rk   ry   	real_sizer   dirpathfilespathsr   dirsr/   select_sizes                          r   checkzCache.checkb  sf   * $$D1 m	U))C /099;D4yA~at!3"& +JWMM'*+ H& ](3  E	2 
 6{++--1 K)E4 " BIMM),yy+$&JJy$9	9,&EG#,i#=D$MM'D.9" #%7%.$6!" !MM"6"BC?%J1K8 *,)A 1%GQHMNHRWWWh7NENJ2E%* 1	!Y.$"4y"@ g/ABIIi01	1  -/GGDOO,D .(GT5 E"7'"A g?HHW-. 

7#!"@AJJL%::&LGMM'TZZ,?"?@I"G, 

6"H -668
$99$JGMM'TYY,="=>H!6Nu]~ [m	 m	n OS] ]m	 m	sW   A5M4CM(#6M(M#
6?M(6AM(8M(;!M(C3M(	M4#M((M1	-M44M=c                 P    | j                   } |d       | j                  dd       y)zCreate tag index on cache database.

        It is better to initialize cache with `tag_index=True` than use this.

        :raises Timeout: if database timeout occurs

        z?CREATE INDEX IF NOT EXISTS Cache_tag_rowid ON Cache(tag, rowid)r$   r   Nr   r   r   r   s     r   r   zCache.create_tag_index  s$     iiMN

;"r
   c                 P    | j                   } |d       | j                  dd       y)z`Drop tag index on cache database.

        :raises Timeout: if database timeout occurs

        z$DROP INDEX IF EXISTS Cache_tag_rowidr$   r   Nr  r  s     r   r   zCache.drop_tag_index  s$     ii23

;"r
   c                 :    d}|ddg}| j                  ||d|      S )a  Remove items with matching `tag` from cache.

        Removing items is an iterative process. In each iteration, a subset of
        items is removed. Concurrent writes may occur between iterations.

        If a :exc:`Timeout` occurs, the first element of the exception's
        `args` attribute will be the number of items removed before the
        exception occurred.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param str tag: tag identifying items
        :param bool retry: retry if database timeout occurs (default False)
        :return: count of rows removed
        :raises Timeout: if database timeout occurs

        zTSELECT rowid, filename FROM Cache WHERE tag = ? AND rowid > ? ORDER BY rowid LIMIT ?r   d   r   )	arg_indexr!  _select_delete)r   r5  r!  r  r   s        r   evictzCache.evict  s3    (& 	
 Q}""641E"JJr
   c                 f    d}d|xs t        j                          dg}| j                  ||d|      S )a  Remove expired items from cache.

        Removing items is an iterative process. In each iteration, a subset of
        items is removed. Concurrent writes may occur between iterations.

        If a :exc:`Timeout` occurs, the first element of the exception's
        `args` attribute will be the number of items removed before the
        exception occurred.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param float now: current time (default None, ``time.time()`` used)
        :param bool retry: retry if database timeout occurs (default False)
        :return: count of items removed
        :raises Timeout: if database timeout occurs

        zuSELECT rowid, expire_time, filename FROM Cache WHERE ? < expire_time AND expire_time < ? ORDER BY expire_time LIMIT ?r   r  r   )	row_indexr!  )r  r  )r   r6  r!  r  r   s        r   r4  zCache.expire  s?    (, 	
 3%$))+s+""641E"JJr
   c                 j   t        j                          }| j                  |      }t        | j                     d   }|y|j	                  d|      }	 | j                         | j                  kD  r| j                  |      5 \  }} ||d      j                         }|s	 ddd       |S |t        |      z  }d|j	                  d|      z  }	 ||	d       |D ]  \  }
 ||
        	 ddd       | j                         | j                  kD  r|S # 1 sw Y   )xY w# t        $ r t        |      dw xY w)	a  Cull items from cache until volume is less than size limit.

        Removing items is an iterative process. In each iteration, a subset of
        items is removed. Concurrent writes may occur between iterations.

        If a :exc:`Timeout` occurs, the first element of the exception's
        `args` attribute will be the number of items removed before the
        exception occurred.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param bool retry: retry if database timeout occurs (default False)
        :return: count of items removed
        :raises Timeout: if database timeout occurs

        r5   Nr   rk   rG  )r!   rF  r=  )r  r4  r   r%   rJ  rI  r&   r"  r   ri   r   )r   r!  r6  r/   rO  rP  r   r;  r<  rQ  rk   s              r   r5   z
Cache.cull2  sF   $ iik C  ((<(<=fE '..jc.J	+++-$//1^^E* *nsG6??AD	*$  SY&E?'..g3.GH  &'+ *)** ++-$//1& %* *  	+%.d*	+s0   .D DD )>D(%D DD D2c                 6    d}ddg}| j                  |||      S )a  Remove all items from cache.

        Removing items is an iterative process. In each iteration, a subset of
        items is removed. Concurrent writes may occur between iterations.

        If a :exc:`Timeout` occurs, the first element of the exception's
        `args` attribute will be the number of items removed before the
        exception occurred.

        Raises :exc:`Timeout` error when database timeout occurs and `retry` is
        `False` (default).

        :param bool retry: retry if database timeout occurs (default False)
        :return: count of rows removed
        :raises Timeout: if database timeout occurs

        zHSELECT rowid, filename FROM Cache WHERE rowid > ? ORDER BY rowid LIMIT ?r   r  r   r  )r   r!  r  r   s       r   clearzCache.cleari  s/    && 	
 3x""64u"==r
   c                 p   d}d}	 	 | j                  |      5 \  }}	 |||      j                         }
|
s	 d d d        |S |t        |
      z  } ||dj                  d |
D              z         |
D ]  }||   ||<    |	|d           	 d d d        # 1 sw Y   
xY w# t        $ r t	        |      d w xY w)Nr   rF  ,c              3   8   K   | ]  }t        |d            yw)r   N)rG   )r   rows     r   r   z'Cache._select_delete.<locals>.<genexpr>  s     )F##c!f+)Fr   )r"  r   ri   r   r   )r   r  r   r  r  r!  r/   rQ  r   r;  r<  r  s               r   r  zCache._select_delete  s     8	+^^E* )nsGvt,557D	)   SY&E)F)F!FFG# )*-i.YB()) ) )  	+%.d*	+s.   B BB  A	B
	B BB B5c              #   *  K   | j                   }d}| j                  j                  }|rd}d}nd}d} ||      j                         }|r|\  \  }}	ny |||	       	  ||||	||f      j                         }
|
sy|
D ]  \  }}	 |||	        4w)a  Iterate Cache keys in database sort order.

        >>> cache = Cache()
        >>> for key in [4, 1, 3, 0, 2]:
        ...     cache[key] = key
        >>> list(cache.iterkeys())
        [0, 1, 2, 3, 4]
        >>> list(cache.iterkeys(reverse=True))
        [4, 3, 2, 1, 0]

        :param bool reverse: reverse sort order (default False)
        :return: iterator of Cache keys

        r  z>SELECT key, raw FROM Cache ORDER BY key DESC, raw DESC LIMIT 1zcSELECT key, raw FROM Cache WHERE key = ? AND raw < ? OR key < ? ORDER BY key DESC, raw DESC LIMIT ?z<SELECT key, raw FROM Cache ORDER BY key ASC, raw ASC LIMIT 1zaSELECT key, raw FROM Cache WHERE key = ? AND raw > ? OR key > ? ORDER BY key ASC, raw ASC LIMIT ?N)r   r   r4   r   )r   reverser   rK  	_disk_getr  iterater  rM   rd   r<  s              r   iterkeyszCache.iterkeys  s      iiJJNN	7 
7 5 
5  &k""$MZc3S!!wc3 67@@BD  *SS))* s   BBc              #   >  K   | j                   } |d      j                         }|\  \  }d  |y |dz   }d}| j                  j                  }|rdn|}d|rdndz  }		 |r|||f}
nd||f}
 ||	|
      j                         }|sy |D ]  \  }}} |||        >w)NzSELECT MAX(rowid) FROM Cacher   r  r   zYSELECT rowid, key, raw FROM Cache WHERE ? < rowid AND rowid < ? ORDER BY rowid %s LIMIT ?r|  r{  )r   r   r   r4   )r   	ascendingr   r<  	max_rowidboundrK  r  r=  r  r   rM   rd   s                r   _iterzCache._iter  s     ii12;;=)AJJNN	E)  UV	- ue,5%(vt$--/D#' *sCS))* s   BBc                 <    | j                         }t        |       |S )z.Iterate keys in cache including expired items.r  nextr   r{   s     r   __iter__zCache.__iter__  s    ::<Xr
   c                 @    | j                  d      }t        |       |S )z6Reverse iterate keys in cache including expired items.F)r  r  r  s     r   __reversed__zCache.__reversed__  s    :::.Xr
   c                     | j                  d      | j                  d      f}|r$| j                  dd       | j                  dd       | j                  d|       |S )zReturn cache statistics hits and misses.

        :param bool enable: enable collecting statistics (default True)
        :param bool reset: reset hits and misses to 0 (default False)
        :return: (hits, misses)

        r1   r2   r   r#   r   )r   enabler   r_   s       r   statszCache.stats	  sR     **V$djj&:;JJvq!JJx#

<(r
   c                     | j                  d      j                         \  \  }| j                  |z  | j                  d      z   }|S )zWReturn estimated total size of cache on disk.

        :return: size in bytes

        zPRAGMA page_countr0   )r   r   r   r   )r   
page_count
total_sizes      r   rI  zCache.volume	  sC      99%89BBD*__z1DJJv4FF
r
   c                     t        | j                  dd      }|y|j                          	 t        | j                  d       y# t        $ r Y yw xY w)zClose database connection.r  N)r
  r   r   delattrAttributeError)r   r  s     r   r   zCache.close!	  sJ    dkk5$/;			DKK' 		s   A 	AAc                     | j                   }| S r   )r  )r   
connections     r   	__enter__zCache.__enter__/	  s     YY
r
   c                 $    | j                          y r   )r   )r   	exceptions     r   __exit__zCache.__exit__5	  s    

r
   c                 $    | j                  d      S )z0Count of items in cache including expired items.r/   r  r   s    r   __len__zCache.__len__8	  s    zz'""r
   c                 Z    | j                   | j                  t        | j                        fS r   )r=   r   rB   r   r   s    r   __getstate__zCache.__getstate__<	  s    d499o>>r
   c                 "     | j                   |  y r   )r>   )r   states     r   __setstate__zCache.__setstate__?	  s    ur
   c                    | j                   }| j                  }|t        u r-d} |||f      j                         \  \  }t	        | ||       |S |rd} ||||f       |j                  d      r]|dd }t        j                         }		 	 	  |d|z        j                         \  \  }
|
|k7  }|r |d|d	|      j                          n-|j                  d      r|dd }t	        | j                  ||       t	        | ||       |S # t        $ r d}Y hw xY w# t        j                  $ rK}t        |      d
k7  r t        j                         |	z
  }|dkD  r t        j                  d       Y d}~nd}~ww xY w)a  Reset `key` and `value` item from Settings table.

        Use `reset` to update the value of Cache settings correctly. Cache
        settings are stored in the Settings table of the SQLite database. If
        `update` is ``False`` then no attempt is made to update the database.

        If `value` is not given, it is reloaded from the Settings
        table. Otherwise, the Settings table is updated.

        Settings with the ``disk_`` prefix correspond to Disk
        attributes. Updating the value will change the unprefixed attribute on
        the associated Disk instance.

        Settings with the ``sqlite_`` prefix correspond to SQLite
        pragmas. Updating the value will execute the corresponding PRAGMA
        statement.

        SQLite PRAGMA statements may be executed before the Settings table
        exists in the database by setting `update` to ``False``.

        :param str key: Settings key for item
        :param value: value for item (optional)
        :param bool update: update database Settings table (default True)
        :return: updated value for item
        :raises Timeout: if database timeout occurs

        z(SELECT value FROM Settings WHERE key = ?r  r      NTz	PRAGMA %szPRAGMA z = r  r   r  r   r   )r   r   r   r   setattrr   r  r   rC   r   rG   r  r   )r   rM   rw   r   r   	sql_retryr  r  pragmar  	old_valuer  r  attrs                 r   r   zCache.resetB	  s   8 iiOO	F??F#FSF3<<>KXeD#u%LEIi%.>>)$WF IIKE&&*-'62+"(* () "+e!3 >?HHJ ^^G$qr7DDJJe,c5!# & &!%&
 // &3x#7799;.DbyJJu%%& s7   
"D ,D DD DD E6+AE11E6)F)FN)NFNFr   )NF)r   r   F)NFFFF)NFFF)T)Nr}  NFNF)NrX  r~  FFF)TFFF)NFNNr   )FF)r   r   F)TF)<r   r   r   r   r8   r>   propertyr=   r   r   r  r   r   r   contextmanagerr#  r"  r?  rB  r1  r2  r3  rT  rV  r_  ra  r4   rl  rt   rq  r   ru  rQ  r  r  r  r  r  r  r   r   r  r4  r5   r  r  r  r  r  r  r  rI  r   r  r  r  r  r  r   r   r   r
   r   r   r     s   %!%r kZ       # #J ! ! # #4  < &' &'P?B	)
:
.0"d#J4lIV6B cJ$( FK<|>. bL ur m^L^ EG]~BH
##K6K65n>6 =B48*t*B&#?  &d Rr
   r   ).r   r   
contextlibr   r   	functoolsrr   rb   r   r   os.pathpathro   rY   r[   rC   rK   r   r   r  r  rE   r	   r   r   r  r   r   	MODE_NONErj   rm   rq   rv   HIGHEST_PROTOCOLr   r   r   r8   r   	Exceptionr   UserWarningr   r   r   r   r   r
   r   <module>r     sj       	  	          5
u  
	(	
9
		 . "33   	 " H# %I$ 1J-Bd$ d$N&t &R$i $9 9=k =<s sr
   