Python Flask - 使所有文件上传到 tmp 目录

标签 python flask

根据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/

相关文章:

python - 检测 Flask 应用程序是否在本地运行

python - 无法确定导致 Flask Werkzeug BuildError 的原因

python - 从 matplotlib `ax` 对象中提取刻度参数

python - 使用 python 的 numpy 从 csv 计算方法

python - 如何在 Anaconda python 发行版上安装 AWSCLI

python - 从 werkzeug.datastructures.FileStorage 计算 md5 而不将对象保存为文件

python - 当我使用 cron 运行时,在 Linux 服务器中找不到某些文件

python - SQLAlchemy:检查两列之一的任何约束不为空?

javascript - Flask,在 Javascript 中提供静态文件和/或文件夹

python - 使用 AJAX 部署的 Flask 应用程序文件上传权限被拒绝