iI dZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZdZGddeZdZedZedZdZd Zd Zd Zd Z ddd ddd dddd de j!d Z"dddddZ#dddddddddddddddddZ$Gd d!Z%Gd"d#e%Z&Gd$d%e'Z(Gd&d'e)Z*Gd(d)e)Z+d*Z,Gd+d,Z-dS)-z%Core disk and file backed cache API. Nc&|jdz|jzS)zBReturn full name of `func` by adding the module and function name..) __module__ __qualname__)funcs n/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/diskcache/core.py full_namer s ?S 4#4 44ceZdZdZdZdZdS)Constantz%Pretty display of immutable constant.c:t||fSN)tuple__new__)clsnames rrzConstant.__new__s}}S4'***r cd|dzS)Nz%srselfs r__repr__zConstant.__repr__"sd1g~r N)__name__rr__doc__rrrr rr r s8//+++r r zcache.dbENOVALUNKNOWNleast-recently-storedi@ i walii) statistics tag_indexeviction_policy size_limit cull_limitsqlite_auto_vacuumsqlite_cache_sizesqlite_journal_modesqlite_mmap_sizesqlite_synchronousdisk_min_file_sizedisk_pickle_protocol)countsizehitsmisses)initgetcullzACREATE 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)zaccess_time = {now}z7SELECT {fields} FROM Cache ORDER BY access_time LIMIT ?zECREATE INDEX IF NOT EXISTS Cache_access_count ON Cache (access_count)zaccess_count = access_count + 1z8SELECT {fields} FROM Cache ORDER BY access_count LIMIT ?)noner zleast-recently-usedzleast-frequently-usedcVeZdZdZd dZdZdZdZefdZ dd Z d Z eefd Z d Z dS)Diskz@Cache key and value serialization for SQLite database and files.rc0||_||_||_dS)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_sizepickle_protocol)r directoryr;r<s r__init__z Disk.__init__js!$*.r cd}||\}}t|}|tjurt j||zS|t ur*t j|d|zS|tur||zS|tusJt jtj d||zS)zgCompute portable hash for `key`. :param key: key to hash :return: hash value lutf-8z!d) puttypesqlite3Binaryzlibadler32strencodeintfloatstructpack)rkeymaskdisk_key_ type_disk_keys rhashz Disk.hashvshhsmm !X GN * *<))D0 0 c ! !< 8 899D@ @ c ! !d? " E))))< D( ; ;<#&&, , __C(CFFFF3FFFFFE!!9 <d.BCCCD )$//F>&))50 0r c|r,t|tjurt|n|St jt 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 )rBrCrDrXrYloadioBytesIO)rrMraws rr4zDisk.getsF  0!%cgn!> 3  "&--U";"; Hi KK 2;u#5#5sG D D D:i((DHd2 2  @Z E22F"&--U";"; HiFC((H;;y(D99Dh4 4\%$2FGGGF6{{]**+tW^F-C-CCC&*mmC&?&?#) Irz&'9'94@@@6{{K4??r Nctj|\}}tddD]}tjt 5t j|dddn #1swxYwY t|||}n#t $r |dkrYnwxYw|5d} |D])} | t| z } | | *| cdddcS#1swxYwYdS)Nr encodingr!r) rosplitrangeclsuppressOSErrorosmakedirsopenriwrite) rryr{moderfull_dirrPr/writerr0chunks rrlz Disk._writeshy)) !1b\\  EW%% & & H%%% & & & & & & & & & & & & & & & iAAA   B;;     %((ECJJ&DLL''''                      s6A$$A( +A( 0BBB0CC "C cf|tkr,t|tjurt |n|S|t kr|r(t tj|j |dSt tj|j |d5}| cdddS#1swxYwYdS|tkrZtj|j |}t |dd5}| cdddS#1swxYwYdS|tkr~|Vt tj|j |d5}tj|cdddS#1swxYwYdStjtj|SdS)aConvert 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 rbNrrhr)rjrBrCrDrXrmrrojoinr:rtrqrvrYrarbrc)rrrkrwrtrzrys rfetchz Disk.fetchsK 8  #';;'.#@#@5<<>EEE"'$/8<>FFc@tjtjddd}t j|dd|dd}|dddz}t j||}t j|j|}||fS)aReturn 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 `, 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@Nrrz.val)codecsrHrurandomdecoderorr:)rrMrwhex_namesub_dirrrkrys rrkz Disk.filenames&=B77>>wGG'(2A2,1 66|f$77D))GDOX66 ""r c~tj|j|}tj|\}}t jt 5tj|dddn #1swxYwYt jt 5tj |ddddS#1swxYwYdS)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) rorr:rrrrrremove removedirs)r file_pathryrrPs rrz Disk.remove8s'GDOY77 hy)) ! [ ! ! ! ! Ii  ! ! ! ! ! ! ! ! ! ! ! ! ! ! ![ ! ! $ $ M( # # # $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $s$ A,,A03A0B22B69B6)rrr)rrrrr>rRrAr4rr|rlrrkrrr rr8r8gsJJ / / / /DDD*1114 0 0 0&-1@1@1@1@f0666@#'####4$$$$$r r8cPeZdZdZdfd ZfdZfdZeffd ZfdZ xZ S) JSONDiskzCCache key and value using JSON serialization with zlib compression.rc J||_tj|fi|dS)aInitialize 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_levelsuperr>)rr=rkwargs __class__s rr>zJSONDisk.__init__Qs2---f-----r ctj|d}tj||j}t |SNr@)jsonrZrHrEcompressrrrA)rrM json_bytesr^rs rrAz JSONDisk.putasHZ__++G44 }Z)<==ww{{4   r ct||}tjt j|dSr)rr4rloadsrE decompressr)rrMrdr^rs rr4z JSONDisk.getfsBww{{3$$z$/$//66w??@@@r c|sAtj|d}tj||j}t |||S)Nr@rM)rrZrHrErrrr|)rrwrtrMrrs rr|zJSONDisk.storejsY CE**11'::JM*d.ABBEww}}UDc}222r ct||||}|s9tjt j|d}|Sr)rrrrrErr)rrrkrwrtr^rs rrzJSONDisk.fetchpsSww}}T8UD99 E:dod33::7CCDDD r )r) rrrrr>rAr4rr|r __classcell__)rs@rrrNsMM...... !!!!! AAAAA&-333333 r rceZdZdZdS)TimeoutzDatabase timeout expired.Nrrrrrr rrrws####r rceZdZdZdS)UnknownFileWarningz.Warning used by Cache.check for unknown files.Nrrr rrr{s8888r rceZdZdZdS)EmptyDirWarningz2Warning used by Cache.check for empty directories.Nrrr rrrs<<<zargs_to_key..s1NN%v:M:M:M:M:M:MNNr rc$i|] \}}|v || Srr)rrMvalrs r zargs_to_key..s)OOOxsCS=N=N#s=N=N=Nr c34K|]}t|VdSrrB)rrs rrzargs_to_key..s(//3T#YY//////r c3:K|]\}}t|VdSrr)rrPrws rrzargs_to_key..s,BBEeBBBBBBr )r enumerateitemssorted)baseargsrtypedrrM sorted_itemsitems ` r args_to_keyrs NNNNyNNN N ND + C OOOO6<<>>OOOfllnn--    D 4KCC C u//$//////  C 5BB\BBBBB BC Jr cPeZdZdZddefdZedZedZedZ edZ ed Z ed Z e jd?d Ze jd@d ZdAdZdZdZdZdBdZdCdZdAdZdDdZdDdZ dEdZdZd?dZdZ dFdZdGdZd?d Z dHd"Z! dId%Z" dId&Z#dJd'Z$ dKd)Z%dLd*Z&d+Z'd,Z(d?d-Z)dCd.Z*d?d/Z+d?d0Z, dMd1Z-d?d2Z.dGd3Z/d4Z0d5Z1dNd6Z2d7Z3d8Z4d9Z5d:Z6d;Z7d<Z8d=Z9e:dfd>Z;dS)OCachezDisk and file backed cache.N<c  t|tsJn%#ttf$rt ddwxYw|t jd}t|}tj |}tj |}||_ d|_ tj|_d|_tj|sa t%j|dnJ#t($r=}|jt*jkrt/|jd|j zdYd}~nd}~wwxYw|j} t3|d}n#t6j$ri}YnwxYwt:}||||t@D]} |!| dtE|#D]2\} } | $d r|%| | d 3|d d |#D} ||fi| |_&|#D]+\} } d} || | | f|%| | ,t@#D]*\} } d} || | | f|%| +|d\\|_'|d|d|dtP|j)d} | || |d|d|d|d|d|j*r|+n|,|-||_ |j.dS)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-)prefixriz.sH   U~~g&& GU   r z-INSERT OR REPLACE INTO Settings VALUES (?, ?)z,INSERT OR IGNORE INTO Settings VALUES (?, ?)zPRAGMA 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)r3zCREATE 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 TypeErrorAssertionError ValueErrortempfilemkdtemprGro expanduser expandvarsr:_timeout threadinglocal_local_txn_idisdirrrrerrnoEEXISTEnvironmentError _sql_retrydictfetchallrCOperationalErrorDEFAULT_SETTINGScopyrMETADATApoprrrreset_disk _page_sizeEVICTION_POLICYr%r$create_tag_indexdrop_tag_indexclose_sql) rr=timeoutdisksettingserrorsqlcurrent_settingssetsrMrwrquerys rr>zCache.__init__s LdD)) ) )) )>* L L L@AAt K L   ( ===I NN M),, M),, # o''  x ""   Iu----   ;%,..* 46:oF  /.... o "#566??AA    ' " " "!    " $$&& $%%% H  C HHS$    !.. 5 5JC~~i(( 5 3e 444       "jjll    T)..v.. **,, # #JCCE CU| $ $ $ JJsE " " " ""..**  JCBE CU| $ $ $ JJsOOOO #$6 7 7 @ @ B B $/          #     45f=   CJJJ  (     (     '     '     '    > "  ! ! # # # #    ! ! !   s2"<C%% D,/3D''D,7*E""E65E6c|jS)zCache directory.)r:rs rr=zCache.directoryQs r c|jS)z+SQLite connection timeout value in seconds.)rrs rrz Cache.timeoutVs }r c|jS)zDisk used for serialization.)rrs rrz Cache.disk[s zr cHt|jdd}tj}||kr |||j_t|jdd}|t jtj |j t|j dx}|j_ d}||}|D]2\}}|dr|||d3n#t j$rYnwxYw|S)Npidcon)risolation_levelrrFr)getattrrrgetpidrr rCconnectrorr:DBNAMErr executerrrr)r local_pidr r selectrrMrws r_conz Cache._con`s/ DK55 ikk    JJLLL!DKOdk5$// ;$+O00 $%%% C$+/ =:;;v..7799#+==JC~~i00= 3e <<<=+     s.)D DDc|jjSr)rrrs rrz Cache._sqls y  r c |jfd}|S)Nc tj} |g|Ri|S#tj$rO}t|dkrtj|z }|dkrtjdYd}~nd}~wwxYwo)NTdatabase is lockedrMbP?)timerCrrGsleep) statementrrstartexcdiffrs r_execute_with_retryz-Cache._sql_retry.._execute_with_retrysIKKE &&3y:4:::6:::/&&&3xx#7779;;.DbyyJu%%%%%%%% & &s #BAA<<Br)rrrs @rrzCache._sql_retrys+i & & & & &#"r Fc#pK||5dVddddS#1swxYwYdS)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)rr#s rtransactzCache.transacts8^^%^ ( (   EEE                  s +//c#K|j}g}|jj}tj}|j}||krd}nC |dd}||_n,#t j$r|rY*| ||tdwxYw ||j fV|r|j|ksJd|_|d|D]} | || dS#t$r#|r|j|ksJd|_|dwxYw)NFTzBEGIN IMMEDIATECOMMITROLLBACK) rrrr get_identrrCrrappend BaseException) rr#rkr filenames _disk_removetidtxn_idbeginrs rr$zCache._transacts}i z( !## &==EE , ,C)*** E#&DL/,,,! +$ X...!t+ , 'y'' ' ' ' |s****# H ! ' '# L&&& ' '    |s****# J   sAA;%A;? B??-C,c(tj}|j|\}} |dn||z} |j|||\} } } }| || | | |f}||| 5\}}|d|| f}|r*|\\}}||||||n||| |||||| ddddS#1swxYwYdS)aSet `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 Nrz;SELECT rowid, filename FROM Cache WHERE key = ? AND raw = ?T rrrAr|r$r _row_update _row_insert_cull)rrMrwexpirerttagr#nowdb_keyrd expire_timer0rrkdb_valuecolumnsrcleanuprowsrowid old_filenames rsetz Cache.sets(ikkjnnS)) $ndd#, )-)9)9%3)9)O)O&dHhT48D.^^E8 , , g3- hjj   <+/(&% %%%  W5555  c7;;; JJsC ) ) )!                  s:BDD D c6|||ddS)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)rArrMrws r __setitem__zCache.__setitem__.s" e4(((((r c R|j}|\}}}}} } |d|||d|||| | |f dS)NzUPDATE Cache SET store_time = ?, expire_time = ?, access_time = ?, access_count = ?, tag = ?, size = ?, mode = ?, filename = ?, value = ? WHERE rowid = ?rr ) rr?r8r<rr:r7r0rrkrws rr3zCache._row_update9sci8?5 S$h        r cT|j}|\}}}} } } |d|||||d||| | | f dS)NzINSERT INTO Cache( key, raw, store_time, expire_time, access_time, access_count, tag, size, mode, filename, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)rr ) rrMrdr8r<rr:r7r0rrkrws rr4zCache._row_insertVsfi8?5 S$h  9        r cZ||jn|}|dkrdSd}|dz}||||f}|rBd|dzz} || ||f|D]\} || |t|z}|dkrdSt|jd} | ||jkrdS| d|} || |f}|r9d| d|z} || |f|D]\} || dSdS)NrzcSELECT %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?r5fieldsr8)r'rrirr%volumer&format)rr8rr=limitr'select_expired_templateselect_expiredr>delete_expiredrk select_policyselect_filenamedeletes rr5z Cache._cullms(- T__5 ?? F  , 1:=s>C#455>>@@  D''1N Cj 1 2 2 2# " " !!!! #d)) #JQ((<=fE  DKKMMDO$C$C F'..jc.JJs?ZM22;;==  "<$$G$==F C & & &# " " !!!! " "  " "r crtj}|j|\}}|dn||z}||5\}} |d||f} | r+| \\} } | | |kr|d|| f ddddSdddn #1swxYwYdS)aTouch `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)rrrAr$r) rrMr6r#r8r9rdr:rrPr>r?old_expire_times rtouchz Cache.touchsDikkjnnS)) $ndd#, ^^E " " hsA3- hjj   .2+)%"*o.C.CCJ$e,                        "usAB,,B03B0cltj}|j|\}} |dn||z} |j|||\} } } }| || | | |f}||| 5\}}|d|| f}|rL|\\}}}|||kr||  ddddS||||||n||| |||||| ddddS#1swxYwYdS)aAdd `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 NrzHSELECT rowid, filename, expire_time FROM Cache WHERE key = ? AND raw = ?FTr2)rrMrwr6rtr7r#r8r9rdr:r0rrkr;r<rr=r>r?r@rUs raddz Cache.adds2ikkjnnS)) $ndd#, )-)9)9%3)9)O)O&dHhT48D ^^E8 , , g3- hjj   <<@97%"*o.C.CGH%%%          %%%  W5555  c7;;; JJsC ) ) )+                  s:AD) AD))D-0D-rrctj}|j|\}}d}||5\} } | |||f} | ss|t |||z} d|j| d|z} ||||| ||| | | cdddS| \\}}}} |||kr}|t |||z} d|j| d|z} | ||| ||| | | || cdddS| |z } d} t|j d}|| d| | zz } d | z}| ||| |f| cdddS#1swxYwYdS) aIncrement 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 = ?NNNFrzstore_time = ?, value = ?r4z, r8#UPDATE Cache SET %s WHERE rowid = ?) rrrAr$rKeyErrorr|r4r5r3rr%rL)rrMdeltadefaultr#r8r9rdrrr=r>rwr<r?r:rk update_columnrs rincrz Cache.incrs2ikkjnnS))  )  ^^E " ") nsG3v}--6688D ?"3--'%&)9)95c*:**  c7;;; 3W---) ) ) ) ) ) ) ) 8< 4 2e[(E&;+<+<?"3--'%&)9)95c*:**  W555 3W---!!!9) ) ) ) ) ) ) ) < UNE1G+D,@A%HM(4-"6"63"6"?"???:WDF CeU+ , , ,S) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) s!B G!BG/AGGGc4||| ||S)a3Decrement 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 )ra)rrMr^r_r#s rdecrz Cache.decrEs8yyufgu555r c,|j|\}}t|jd} d} |r|r|ddf}n|s|r|df}|js| }|| ||t jf} | s|S| \\} } }}}} |j||||}nA#t$r|cYSwxYwd}d}| |5\}}|| ||t jf} | s |jr |||cdddS| \\} } }}}} |j||||}n0#t$r#|jr |||cYcdddSwxYw|jr ||t j}d}| $||| |z| fdddn #1swxYwY|r|r|| |fS|r|| fS|r||fS|S)aRetrieve 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 r4SELECT 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"r\r[) rrArr%r#rrrrIOErrorr$rL)rrMr_rtr:r7r#r9rdr`rr>r?db_expire_timedb_tagrrkr;rw cache_hit cache_missrrPr8rs rr4z Cache.getcse4jnnS)) '(<=eD  <   &3 &d+GG  &C &oG3 J=#899Vfc49;;%?@@IIKKD KO H Fe^VT8X  ((x4HH     K M && J(3s6FC#=>>GGII#(J"  J J J J J J J JMUNFD(H# J,,T8XtLLEE###(J"NN% J J J J J J J J# ?#C NNNikk> ,C!5!5#!5!>!>>III7 J J J J J J J J J J J J J J J:  3 >62 2  >* *  6? "LsPB>> C  C )A G4 G4 E+*G4+F G4FAG44G8;G8cp||td}|turt||S)zReturn corresponding value for `key` from cache. :param key: key matching item :return: corresponding value :raises KeyError: if key is not found Tr_r#r4rr]rCs r __getitem__zCache.__getitem__s5fD99 F??3--  r cr||td|}|turt||S)aReturn 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_rtr#rm)rrMr#handles rrtz Cache.reads9#vDFF V  3--  r c|j}|j|\}}d}||||tjf}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 > ?))rrrArrbool)rrMrr9rdrr>s r __contains__zCache.__contains__sdijnnS))  <  s6FC566??AADzzr c|j|\}}d}|r|r|ddf}n|s|r|df}||5\} } | |||tjf} | s|cdddS| \\} } }}}}| d| fdddn #1swxYwY |j|||d}n/#t $r"|cY||j|SSwxYw ||j|n"#||j|wwxYw|r|r|| |fS|r|| fS|r||fS|S)aRemove 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 reN!DELETE FROM Cache WHERE rowid = ?F)rrAr$rrrrfr)rrMr_r:r7r#r9rdrrrPr>r?rgrhrrkr;rws rrz Cache.popsM,jnnS))  <   $3 $tT)GG  $C $tmG ^^E " " ?hsA3vTY[[9::CCEED   ? ? ? ? ? ? ? ? LP H Fe^VT8X C3eX > > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ,J$$T8XuEEEE   NN# !!(++++$    # !!(+++# !!(++++$  3 .&0 0  .( (  &= LsB9B1 B11B58B5=CD( D'D(DD((ETch|j|\}}||5\}}|d||tjf}|st ||\\}} |d|f||  ddddS#1swxYwYdS)aDelete 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 > ?)ruNT)rrAr$rrr]) rrMr#r9rdrr=r>r?rks r __delitem__zCache.__delitem__8sjnnS))  ^^E " " nsG3@dikk*  hjj  $smm##' eX C3eX > > > GH                     sA'B''B+.B+cT |||S#t$rYdSwxYw)aDelete 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)rwr])rrMr#s rrSz Cache.deleteWsB ##Cu#55 5   55 s  ''backc|d}d} n |dz}|dz} tj} d} |dn| |z} |j||\} }}}| || |||f}ddd }d ||z}|||5\}}|||| | f}|rR|\\}|.t ||d d zd}n|}|d kr|d z }n|dksJ|d z}nd}|d||}n|}||| | || | |||cdddS#1swxYwYdS)aPush `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 NrI5-000000000000000-999999999999999TDESCASC)ryfrontzSSELECT key FROM Cache WHERE ? < key AND key < ? AND raw = ? ORDER BY key %s LIMIT 1-rryrl@$z {0}-{1:015d}) rrr|r$rrIrfindrLr4r5)rrwrsider6rtr7r#min_keymax_keyr8rdr:r0rrkr;r<orderrrr=r>rMnumr9s rpushz Cache.pushks h >G%GG11G11Gikk$ndd#, )-)9)9%)F)F&dHhT48D%00 ' $K  ^^E8 , , g3v#677@@BBD & #%c399S>>A#5"8"89::CCC6>>1HCC7????1HCC%!'..vs;;   VS#w 7 7 7 JJsC ) ) )7                  s>CEEErZrc|d}d}n |dz}|dz}ddd} d | |z} |r|r|ddf}n|s|r|df} ||5\} } | | ||f} | s|cdddS| \\}}}}}}}| d |f|#|tjkr | |n dddn dddn #1swxYwY |j|||d }n,#t $rY||j|wxYw ||j|n"#||j|wwxYw |r |r||f||fS|r||f|fS|r||f|fS||fS) 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 Nrr{r|r}rr~rrySELECT rowid, key, expire_time, tag, mode, filename, value FROM Cache WHERE ? < key AND key < ? AND raw = 1 ORDER BY key %s LIMIT 1TruF)r$rrrrrfrrrr_rr:r7r#rrrrrr=r>r?rM db_expirerhrrr;rws rpullz Cache.pulls| >G%GG11G11G00 ' $K   $3 $tT)GG  $C $tmG  ^^E**nsG3v'9::CCEED'& MYdHC;eXFFF ,TY[[1H1H & $ , ((tXuEE   #J%%d+++   #J%%d+++#J%%d++++$   3 <F2 2  <* *  <' ': sB 'C??CCC$DE  D+ E *D++E E+cd|d}d}n |dz}|dz}ddd} d | |z} |r|r|ddf}n|s|r|df} ||5\} } | | ||f} | s|cdddS| \\}}}}}}}|0|tjkr| d |f| |n dddn dddn #1swxYwY |j|||d }n#t $rYwxYw |r |r||f||fS|r||f|fS|r||f|fS||fS) aPeek 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 Nrr{r|r}rr~rrTruF)r$rrrrrfrs rpeekz Cache.peekFsrt >G%GG11G11G00 ' $K   $3 $tT)GG  $C $tmG  ^^E**nsG3v'9::CCEED'& MYdH!,TY[[1H1H?%JJJ & "  ((tXuEE       3 <F2 2  <* *  <' ': s* 'C??CCC$D DDc Ld}d||z} ||5\}}||} | std| \\} } } } }}}}| 0| tjkr|d| f||n dddn dddn #1swxYwY|j| | } |j|||d}n#t$rYwxYw |r |r||f| |fS|r||f| fS|r||f|fS||fS)aPeek 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 )rr~zdSELECT rowid, key, raw, expire_time, tag, mode, filename, value FROM Cache ORDER BY rowid %s LIMIT 1Tzdictionary is emptyNruF)r$rr]rrr4rrf)rlastr:r7r#rrrr=r>r?r9rdrrhrrr;rMrws rpeekitemzCache.peekitems6  4 $K "  ^^E**nsG3v;;//11D>&'<===  !"%"  $!,TY[[1H1H?%JJJ /*&+ 4*..--C  ((tXuEE       3 <F2 2  <* *  <' ': s$A2B00B47B4C66 DDrcbtrtdfd}|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 zname cannot be callablectfnftjfd fd}|_S)z3Decorator created by memoize() for callable `func`.Ncj|i|}|td}|tur*|i|}dkr||d|S)z:Wrapper for callable to cache arguments and return values.TrlNr)r7r#) __cache_key__r4rrA) rrrMr_r6rrr7wrappers rrz1Cache.memoize..decorator..wrapperLs,g+T.decorator..__cache_key__Ys"4vufEEEr )r rrwrapsr) rrrrr6rrrr7rs ` @@r decoratorz Cache.memoize..decoratorHs)-IdOO%%D7D Xd^^        ^  F F F F F F F%2G !Nr )callabler)rrrr6r7rrs`````` rmemoizez Cache.memoizesbD D>> 7566 6          0r ctjd5}|j}|d}t |dks|dddkr|D]\}tj||r |d||5\}}t}d} || }|D]\} } } tj |j | } | | tj | rItj | }| |kr.d }| || f}tj||z|r|d || ftjd | z|r |d | ftj|j D]j\}}fd |D}t||z }|D]A} t | vr d| z}tj|t"|rtj| Bktj|j D]?\}}|s7|s5dz}tj|t&|rtj@|d|d\\}|j|kr0d}tj||j|fz|r|d|df|dd}||\\} |j| kr0d}tj||j| fz|r|d| dfdddn #1swxYwY|cdddS#1swxYwYdS)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)recordzPRAGMA integrity_checkrrokVACUUMzBSELECT rowid, size, filename FROM Cache WHERE filename IS NOT NULLzwrong file size: %s, %d != %dz)UPDATE Cache SET size = ? WHERE rowid = ?zfile not found: %sruc:g|]}tj|Sr)ror)rrkdirpaths r zCache.check..s%NNNHRWWh77NNNr zunknown file: %szempty directory: %sr/zSELECT COUNT(key) FROM Cachez,Settings.count != COUNT(Cache.key); %d != %d+UPDATE Settings SET value = ? WHERE key = ?r0z(SELECT COALESCE(SUM(size), 0) FROM Cachez*Settings.size != SUM(Cache.size); %d != %dz*UPDATE Settings SET value = ? WHERE key =?N)warningscatch_warningsrrriwarnr$rArorr:rXexistsrprwalkrrrrrmdirrr/r0)rfixr#warnsrr>messagerPr,rr?r0rkry real_sizerfilespathsrdirsr/ select_sizers @rcheckz Cache.checkbs* $D 1 1 1m U)C3/0099;;D4yyA~~at!3!3"&++JWM'**** H &&] (3 EE 2 s6{{++---1KK)E4 " B BIMM),,,y++!$&Jy$9$9 9,,&EG#,i#=D$M'D.999"" #%7%.$6!"!"!" !M"6"BCCCK?%JJJ*,)A)A 1 1%GQNNNNNNNEJJ2E%*11 !Y..$"4y"@ g/ABBB1Ii0001-/GDO,D,D..(GT5 .E."7'"A g???.HW--- 7###!c"@AAJJLL %:&&LGM'TZ,?"?@@@I"G, 6"""H  S--6688 $9$$JGM'TY,="=>>>H!6Nu] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~[m m m m m m m m m m m m m m m m m m s7BM0J-M M0M M0M M00M47M4cV|j}|d|dddS)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$rNrrrrs rrzCache.create_tag_indexs6i  MNNN ;"""""r cV|j}|d|dddS)z`Drop tag index on cache database. :raises Timeout: if database timeout occurs z$DROP INDEX IF EXISTS Cache_tag_rowidr$rNrrs rrzCache.drop_tag_indexs6 i  2333 ;"""""r cBd}|ddg}|||d|S)aRemove 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 ?rdr) arg_indexr#_select_delete)rr7r#rrs revictz Cache.evicts6( &  Q}""641E"JJJr chd}d|ptjdg}|||d|S)aRemove 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 ?rrr) row_indexr#)rr)rr8r#rrs rr6z Cache.expiresB( ,  3%$)++s+""641E"JJJr ctj}||}t|jd}|dS|d|} ||jkr||5\}}||d}|s dddn|t|z }d|d|z} || d|D]\} ||  dddn #1swxYwY||jkn#t$rt|dwxYw|S) aCull 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 r5NrrkrI)r!rHr?) rr6rr%rLrKr&r$rrir) rr#r8r/rQrRrr=r>rSrks rr5z Cache.cull2s$ikk C  ((<=fE  1'..jc.JJ +++--$/11^^E***nsG366??AAD ******* SYY&E?'..g3.GGHC&&&'+** ))))****************++--$/11  + + +%..d * + s=2E%D4 EA D EDED EEc>d}ddg}||||S)aRemove 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 ?rrr"r)rr#rrs rclearz Cache.clearis2& &  3x""64u"===r cd}d} ||5\}} |||} | s dddnw|t| z }||dd| Dz| D]} | |||<| | d dddn #1swxYwYn#t$rt |dwxYw|S)NrrHT,c3@K|]}t|dVdS)rN)rG)rrows rrz'Cache._select_delete..s,)F)F##c!f++)F)F)F)F)F)Fr )r$rrirr) rrrrrr#r/rSrr=r>rs rrzCache._select_deletes8 + )^^E** )nsG3vt,,5577D ) ) ) ) ) ) ) SYY&EC)F)F)F)F)F!F!FFGGG#))*-i.YB(((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) + + +%..d * + s;C%B8 C AB8, C8B<<C?B<CC c#0K|j}d}|jj}|rd}d}nd}d}||}|r|\\}} ndS||| V |||| ||f} | sdS| D]\}} ||| V=)aIterate 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 rz>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