根据docs ,如果文件“相当小”(没有提到上限),Flask 会将上传的文件存储在内存中,否则存储在 tempfile.gettempdir()
返回的临时位置。
如何让它将所有文件存储到临时目录?
最佳答案
根据Flask
doc ,上传文件的处理实际上是由其底层来处理的werkzeug WSGI 实用程序库。
根据werkzeug's documentation正如您提到的“相当小”,获取文件的 temp
位置的下限是 500KB
。
The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters.
让我们看看上限。根据aforementioned Flask
doc ,
By default Flask will happily accept file uploads to an unlimited amount of memory,but you can limit that by setting the
MAX_CONTENT_LENGTH
config key.
例如这个代码片段
from flask import Flask, Request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
will limited the maximum allowed payload to 16 megabytes. If a larger file is transmitted, Flask will raise an
werkzeug.exceptions.RequestEntityTooLarge
exception.
现在,回答您的核心问题
How can I make it store ALL files to the temporary directory?
您可以通过覆盖 default_stream_factory()
来做到这一点功能:
def default_stream_factory(total_content_length, filename, content_type, content_length=None):
"""The stream factory that is used per default."""
# if total_content_length > 1024 * 500:
# return TemporaryFile('wb+')
# return BytesIO()
return TemporaryFile('wb+')
关于Python Flask - 使所有文件上传到 tmp 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057730/