flask實現檔案的上傳

2022-07-15 01:15:10 字數 1515 閱讀 8284

檔案上傳過程中,一定要進行檔案大小的校驗,如果使用者上傳檔案過大,比如:100gb,所以一直在處理這個請求,別的請求進來就無法處理了,所以要限制上傳檔案的大小。

flask中,提供了校驗檔案大小的機制,所以在配置檔案中進行配置,並重寫異常返回資訊即可。

自定製錯誤返回資訊

在flask內部,會幫我們校驗,如果上傳檔案大於設定,會返回乙個 413 的異常

所以自定義這個413的異常資訊

deferror(arg):

ret = make_response('

上傳檔案最大支援:5m')

ret.status_code = 413

return ret

自定製異常資訊

這個在mac和linux上不報錯,但是在windows下會報錯,解決方式

from gevent.pywsgi import

wsgiserver

from flask import

flask,request,render_template,make_response)'

max_content_length'/

')defhello():

return

'hello world''

/upload

',methods=['

get','

post'])

defupload():

if request.method == '

post':

file = request.files.get('

file')

print

(file.stream)

return render_template('

upload.html')

deferror(arg):

ret = make_response('

上傳檔案最大支援:5m')

解決windows下的報錯

需要借助python標準庫中的shutil模組的兩個方法

壓縮:shutil.make_archive("檔案壓縮後存放的路徑","壓縮的格式","要壓縮的檔案路徑")      

解壓:解壓tar包   shutil._unpack_tarfile("要解壓的檔案路徑或者乙個bytes型別的檔案物件","解壓後檔案的存放路徑")     

解壓zip包    shutil._unpack_zipfile()   

備註:壓縮檔案中還有中文檔名會報錯      

Flask 檔案上傳

class movieform flaskform url filefield label 檔案 validators datarequired 請上傳檔案!description 檔案 def change filename filename fileinfo os.path.splitext f...

自學 Flask 系列(一)實現檔案上傳

flask 是乙個微型的 python 開發的 web 框架,基於werkzeug wsgi工具箱和jinja2 模板引擎。flask使用bsd授權。flask也被稱為 microframework 因為它使用簡單的核心,用extension增加其他功能。flask沒有預設使用的資料庫 窗體驗證工具...

python利用flask實現檔案上傳並儲存

usr bin python3 encoding utf 8 來自官網,但官網的不能直接用,稍微修改了一下,秒秒鐘執行成功,哈哈哈哈 import os from flask import flask,request,redirect,url for from werkzeug.utils impo...