<s> from logging import getLogger <EOL> from os . path import join as path_join , dirname , normpath <EOL> from tornado . web import RequestHandler <EOL> from turbulenz_local . models . gamelist import get_game_by_slug <EOL> from turbulenz_local . tools import get_absolute_path , create_dir <EOL> LOG = getLogger ( __name__ ) <EOL> class SaveFileHandler ( RequestHandler ) : <EOL> def set_default_headers ( self ) : <EOL> self . set_header ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def post ( self , slug , filename ) : <EOL> """<STR_LIT>""" <EOL> game = get_game_by_slug ( slug ) <EOL> if not game : <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' % slug } ) <EOL> if not filename : <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if '<STR_LIT:..>' in filename : <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> content_type = self . request . headers . get ( '<STR_LIT:Content-Type>' , '<STR_LIT>' ) <EOL> if content_type and '<STR_LIT>' in content_type : <EOL> content = self . get_argument ( '<STR_LIT:content>' ) <EOL> binary = False <EOL> else : <EOL> content = self . request . body <EOL> binary = True <EOL> self . request . body = None <EOL> self . request . arguments = None <EOL> file_path = path_join ( get_absolute_path ( game . get_path ( ) ) , normpath ( filename ) ) <EOL> file_dir = dirname ( file_path ) <EOL> if not create_dir ( file_dir ) : <EOL> LOG . error ( '<STR_LIT>' , file_dir ) <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> if content : <EOL> if not binary : <EOL> try : <EOL> content = content . encode ( '<STR_LIT:utf-8>' ) <EOL> except UnicodeEncodeError as e : <EOL> LOG . error ( '<STR_LIT>' , str ( e ) ) <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> LOG . info ( '<STR_LIT>' , file_path , len ( content ) ) <EOL> else : <EOL> LOG . info ( '<STR_LIT>' , file_path ) <EOL> try : <EOL> file_obj = open ( file_path , '<STR_LIT:wb>' ) <EOL> try : <EOL> file_obj . write ( content ) <EOL> finally : <EOL> file_obj . close ( ) <EOL> except IOError as e : <EOL> LOG . error ( '<STR_LIT>' , file_path , str ( e ) ) <EOL> self . set_status ( <NUM_LIT> ) <EOL> return self . finish ( { '<STR_LIT>' : False , '<STR_LIT>' : '<STR_LIT>' } ) <EOL> return self . finish ( { '<STR_LIT>' : True } ) </s>
