Python and Flask - Trying to have a function return a file content -


i struggling return file content user. have flask code receives txt file user, python function transform() called in order parse infile, both codes doing job.

the issue happening when trying send (return) new file (outfile) user, flask code working ok. don´t know how have python transform function() "return" file content, have tested several options already.

following more details:

def transform(filename):      open(os.path.join(app.config['upload_folder'],filename), "r") infile:         open(os.path.join(app.config['upload_folder'], 'file_parsed_1st.txt'), "w") file_parsed_1st:              p = ciscoconfparse(infile)             '''              parsing file uploaded user ,              generating result in new file(file_parsed_1st.txt)               working ok             '''      open (os.path.join(app.config['upload_folder'], 'file_parsed_1st.txt'), "r") file_parsed_2nd:         open(os.path.join(app.config['upload_folder'], 'file_parsed_2nd.txt'), "w") outfile:             '''             file_parsed_1st.txt temp file, creates new file (file_parsed_2nd.txt)             part working ok, new file (file_parsed_2nd.txt)              has results want after parsing;             want new file(file_parsed_2nd.txt) "return" user             '''      #editing -       #here having hard time, , working ok     #using follwing line:          return send_file(os.path.join(app.config['upload_folder'], 'file_parsed_2nd.txt'))  

you need use flask.send_file() callable produce proper response, need pass in filename or file object isn't closed or closed. passing in full path do:

return send_file(os.path.join(app.config['upload_folder'], 'file_parsed_2nd.txt')) 

when pass in file object cannot use with statement, it'll close file object moment return view; it'll read when response object processed wsgi response, outside of view function.

you may want pass in attachment_filename parameter if want suggest filename browser save file as; it'll determine mimetype. may want specify mimetype explicitly, using mimetype parameter.

you use flask.send_from_directory() function; same takes filename , directory:

return send_from_directory(app.config['upload_folder'], 'file_parsed_2nd.txt') 

the same caveat mimetype applies; .txt default mimetype text/plain. function joins directory , filename (with flask.safe_join() applies additional safety checks prevent breaking out of directory using .. constructs) , passes on flask.send_file().


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -