<s> import json <EOL> import os <EOL> import shutil <EOL> import tempfile <EOL> from time import time <EOL> from . compat import is_win32 <EOL> if is_win32 : <EOL> xdg_cache = os . environ . get ( "<STR_LIT>" , <EOL> os . path . expanduser ( "<STR_LIT>" ) ) <EOL> else : <EOL> xdg_cache = os . environ . get ( "<STR_LIT>" , <EOL> os . path . expanduser ( "<STR_LIT>" ) ) <EOL> cache_dir = os . path . join ( xdg_cache , "<STR_LIT>" ) <EOL> class Cache ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , filename , key_prefix = "<STR_LIT>" ) : <EOL> self . key_prefix = key_prefix <EOL> self . filename = os . path . join ( cache_dir , filename ) <EOL> self . _cache = { } <EOL> def _load ( self ) : <EOL> if os . path . exists ( self . filename ) : <EOL> try : <EOL> with open ( self . filename , "<STR_LIT:r>" ) as fd : <EOL> self . _cache = json . load ( fd ) <EOL> except : <EOL> self . _cache = { } <EOL> else : <EOL> self . _cache = { } <EOL> def _prune ( self ) : <EOL> now = time ( ) <EOL> pruned = [ ] <EOL> for key , value in self . _cache . items ( ) : <EOL> expires = value . get ( "<STR_LIT>" , time ( ) ) <EOL> if expires <= now : <EOL> pruned . append ( key ) <EOL> for key in pruned : <EOL> self . _cache . pop ( key , None ) <EOL> return len ( pruned ) > <NUM_LIT:0> <EOL> def _save ( self ) : <EOL> fd , tempname = tempfile . mkstemp ( ) <EOL> fd = os . fdopen ( fd , "<STR_LIT:w>" ) <EOL> json . dump ( self . _cache , fd , indent = <NUM_LIT:2> , separators = ( "<STR_LIT:U+002C>" , "<STR_LIT>" ) ) <EOL> fd . close ( ) <EOL> try : <EOL> if not os . path . exists ( os . path . dirname ( self . filename ) ) : <EOL> os . makedirs ( os . path . dirname ( self . filename ) ) <EOL> shutil . move ( tempname , self . filename ) <EOL> except ( IOError , OSError ) : <EOL> os . remove ( tempname ) <EOL> def set ( self , key , value , expires = <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:7> ) : <EOL> self . _load ( ) <EOL> self . _prune ( ) <EOL> if self . key_prefix : <EOL> key = "<STR_LIT>" . format ( self . key_prefix , key ) <EOL> expires += time ( ) <EOL> self . _cache [ key ] = dict ( value = value , expires = expires ) <EOL> self . _save ( ) <EOL> def get ( self , key , default = None ) : <EOL> self . _load ( ) <EOL> if self . _prune ( ) : <EOL> self . _save ( ) <EOL> if self . key_prefix : <EOL> key = "<STR_LIT>" . format ( self . key_prefix , key ) <EOL> if key in self . _cache and "<STR_LIT:value>" in self . _cache [ key ] : <EOL> return self . _cache [ key ] [ "<STR_LIT:value>" ] <EOL> else : <EOL> return default <EOL> __all__ = [ "<STR_LIT>" ] </s>
