Flask 下載文件及make_response


一、flask向前端提供下載文件的api

@charts.route('/files') @func_time def get_file(): """ http://127.0.0.1:5000/charts/files send_file( filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None) filename_or_fp:要發送文件的文件名 mimetype:如果指定了文件的媒體類型(文件類型),指定了文件路徑將自動進行檢測,否則將引發異常。 as_attachment:如果想要以附件的形式將文件發給客戶端應設為True。經測試如果為True會被下載到本地。 attachment_filename:需要配合as_attachment=True使用,將下載的附件更改成我們指定的名字。 add_etags=True:設置為“false”以禁用附加etags。 :return: """ # 文件的目錄 # file_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statics') # return send_from_directory(file_dir, '孫.xls') # 發送文件夾下的文件 # 文件的絕對路徑 # file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statics', '孫.xls') # return send_file(file_path) # 直接發送文件名 return charts.send_static_file('孫.xls') # 發送靜態文件 
  1. 經使用發現,暫未找到可以指定下載文件的名稱,默認都是已url路徑為文件名進行下載,如本例,下載的文件會以files.xls 下載,並不會以孫.xls 文件名下載
  2. 三種提供下載文件的api send_from_directorysend_filesend_static_file
  • 待解決問題
  1. 如果按文件的原始名稱下載,或者指定名稱下載?
1. 不成熟解決,就是用戶將要下載下來的文件名傳遞過來,而項目中路由配置成允許傳參的路徑即`/files/<file_path>` @app.route("/download/<filepath>", methods=['GET']) def download_file(filepath): # 此處的filepath是文件的路徑,但是文件必須存儲在static文件夾下, 比如images\test.jpg return app.send_static_file(filepath) 

二、make_response的使用

# 測試內置make_response方法的使用 @charts.route('/make_response') def test_response(): """ http://127.0.0.1:5000/charts/make_response :return: """ # 返回內容 # response = make_response('<h3>奮斗中,you can just try it!!!</h3>') # return response # 返回頁面 # response = make_response(render_template('hello.html')) # return response # 返回頁面同時返回指定的狀態碼 # response = make_response(render_template('hello.html'), 2000) # return response # 也可以直接返回狀態碼 response = make_response(render_template('hello.html')) return response, 2001 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM