<s> import os <EOL> import tempfile <EOL> from dimagi . utils . decorators . memoized import memoized <EOL> def Temp ( tmp ) : <EOL> cls = PathTemp if isinstance ( tmp , basestring ) else StringIOTemp <EOL> return cls ( tmp ) <EOL> class TempBase ( object ) : <EOL> @ property <EOL> def file ( self ) : <EOL> return open ( self . path , '<STR_LIT:rb>' ) <EOL> class PathTemp ( TempBase ) : <EOL> def __init__ ( self , path ) : <EOL> self . path = path <EOL> @ property <EOL> def payload ( self ) : <EOL> with open ( self . path , '<STR_LIT:rb>' ) as f : <EOL> return f . read ( ) <EOL> def delete ( self ) : <EOL> os . remove ( self . path ) <EOL> class StringIOTemp ( TempBase ) : <EOL> def __init__ ( self , buffer ) : <EOL> self . buffer = buffer <EOL> self . _path = None <EOL> @ property <EOL> def payload ( self ) : <EOL> return self . buffer . getvalue ( ) <EOL> @ property <EOL> def path ( self ) : <EOL> if self . _path is None : <EOL> fd , path = tempfile . mkstemp ( ) <EOL> with os . fdopen ( fd , '<STR_LIT:wb>' ) as file : <EOL> file . write ( self . buffer . getvalue ( ) ) <EOL> self . _path = path <EOL> return self . _path <EOL> def delete ( self ) : <EOL> if self . _path is not None : <EOL> os . remove ( self . _path ) <EOL> class ExportFiles ( object ) : <EOL> def __init__ ( self , file , checkpoint , format = None ) : <EOL> self . file = Temp ( file ) <EOL> self . checkpoint = checkpoint <EOL> self . format = format <EOL> def __enter__ ( self ) : <EOL> pass <EOL> def __exit__ ( self , exc_type , exc_val , exc_tb ) : <EOL> self . file . delete ( ) </s>
