<s> import hashlib <EOL> import os <EOL> from lockfile import LockFile <EOL> from lockfile . mkdirlockfile import MkdirLockFile <EOL> from . . cache import BaseCache <EOL> from . . controller import CacheController <EOL> def _secure_open_write ( filename , fmode ) : <EOL> flags = os . O_WRONLY <EOL> flags |= os . O_CREAT | os . O_EXCL <EOL> if hasattr ( os , "<STR_LIT>" ) : <EOL> flags |= os . O_NOFOLLOW <EOL> if hasattr ( os , "<STR_LIT>" ) : <EOL> flags |= os . O_BINARY <EOL> try : <EOL> os . remove ( filename ) <EOL> except ( IOError , OSError ) : <EOL> pass <EOL> fd = os . open ( filename , flags , fmode ) <EOL> try : <EOL> return os . fdopen ( fd , "<STR_LIT:wb>" ) <EOL> except : <EOL> os . close ( fd ) <EOL> raise <EOL> class FileCache ( BaseCache ) : <EOL> def __init__ ( self , directory , forever = False , filemode = <NUM_LIT> , <EOL> dirmode = <NUM_LIT> , use_dir_lock = None , lock_class = None ) : <EOL> if use_dir_lock is not None and lock_class is not None : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if use_dir_lock : <EOL> lock_class = MkdirLockFile <EOL> if lock_class is None : <EOL> lock_class = LockFile <EOL> self . directory = directory <EOL> self . forever = forever <EOL> self . filemode = filemode <EOL> self . dirmode = dirmode <EOL> self . lock_class = lock_class <EOL> @ staticmethod <EOL> def encode ( x ) : <EOL> return hashlib . sha224 ( x . encode ( ) ) . hexdigest ( ) <EOL> def _fn ( self , name ) : <EOL> hashed = self . encode ( name ) <EOL> parts = list ( hashed [ : <NUM_LIT:5> ] ) + [ hashed ] <EOL> return os . path . join ( self . directory , * parts ) <EOL> def get ( self , key ) : <EOL> name = self . _fn ( key ) <EOL> if not os . path . exists ( name ) : <EOL> return None <EOL> with open ( name , '<STR_LIT:rb>' ) as fh : <EOL> return fh . read ( ) <EOL> def set ( self , key , value ) : <EOL> name = self . _fn ( key ) <EOL> try : <EOL> os . makedirs ( os . path . dirname ( name ) , self . dirmode ) <EOL> except ( IOError , OSError ) : <EOL> pass <EOL> with self . lock_class ( name ) as lock : <EOL> with _secure_open_write ( lock . path , self . filemode ) as fh : <EOL> fh . write ( value ) <EOL> def delete ( self , key ) : <EOL> name = self . _fn ( key ) <EOL> if not self . forever : <EOL> os . remove ( name ) <EOL> def url_to_file_path ( url , filecache ) : <EOL> """<STR_LIT>""" <EOL> key = CacheController . cache_url ( url ) <EOL> return filecache . _fn ( key ) </s>
