我们可以在上传python-flask之前计算上传文件的大小吗 [英] can we count the upload filesize before uploading in python-flask
问题描述
我有一个简单的flask应用程序,其中我正在上传单个文件,但文件大小小于5MB
为此,我在flask-app中定义了
if request.content_length < 5.250e+6: ## setting upload limit to 5MB
测试用例;但这是在上传后验证文件大小;还是我错了.
所以有什么方法可以在上传之前获取文件大小?
I have a simple flask app where i am uploading single file but with file size of less than 5MB
for that i have defined if request.content_length < 5.250e+6: ## setting upload limit to 5MB
test case in my flask-app; but this is verifying the file size after uploading it; or may be i am wrong.
so is there any way to get the file size before uploading it???
这是python 解决方案 + GAE,但我是python网络框架的新手;我对flask
知之甚少,而该解决方案是基于webapp2的,这对我和GAE来说都很复杂;那是另一个故事.
因此任何人都可以在flask
中生成等效的flask
或任何其他可能的方式?
Here is python solution on python+GAE, but i am new to python web framework; i know very little in flask
and this solution is based on webapp2 which is very complicated for me and also its on GAE; that is another story.
so can anyone generate its flask
equivalent or any other possible way to do it in flask
???
推荐答案
这是AudriusKažukauskas答案的扩展版本:
This is a bit expanded version of Audrius Kažukauskas's answer:
所以有什么方法可以在上传之前获取文件大小?
so is there any way to get the file size before uploading it???
否.
根据 werkzeug的文档处理上传的文件,您不能在所有浏览器不能保证上传之前验证内容大小.仅保证request
中所有数据的总内容长度在此.网络浏览器.因此,Flask/werkzeug只能在文件上传后强制执行检查.
No.
As per werkzeug's documentation that Flask
use to handle uploaded file, you cannot verify the content-size before uploading is NOT guaranteed by all browsers. Only the total content-length of all the data in the request
is guaranteed to be there. web-browsers. Hence, Flask/werkzeug can enforce checking only after file-upload.
但是,为避免Web服务器因内存溢出而崩溃,可以并且应该限制可上传的大小.这是配置变量MAX_CONTENT_LENGTH
,您可以在应用程序的配置文件中提及.
However, to avoid crashing of your web-server from memory-overflow, you can and should limit the upload-able size. Here comes the config variable MAX_CONTENT_LENGTH
which you can mention in app's config file.
from flask import Flask, Request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # for 16MB max-limit.
但是,对于任何严肃的应用程序,您应该考虑使用Flask-plugin Flask-Uploads 允许使用更高级的选项,例如将某些文件类型列入白名单和黑名单,基于类型的上传规则,可配置的上传目标等.
However, for any serious application, you should consider using the Flask-plugin Flask-Uploads which allows more advanced options such as white-listing and black-listing certain file-types, type-based upload rules, configurable upload destinations etc.
您可以提问 为什么我应该寻求额外的扩展 .
因为Flask
是一个微框架.不是万能的框架.
You can question why should i go for the extra extension.
Because, Flask
is a micro-framework. Not a do-it-all framework.
这篇关于我们可以在上传python-flask之前计算上传文件的大小吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!