使用Flask-Uploads拒绝大于一定数量的文件?

时间:2015-08-07 09:15:40

标签: python file-upload flask flask-uploads

Flask建议使用Flask-Uploads模块来处理上传。我想拒绝任何超过一定大小的文件。有一些解决方案可供选择:

From the docs

  

此外,您还可以使用patch_request_class修补应用的request_class,使其具有上传的最大大小。

patch_request_class(app, 32 * 1024 * 1024)

From this SO post

  

MAX_CONTENT_LENGTH是拒绝大于您想要的文件上传的正确方法,

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# save to disk first, then check filesize
request.files['file'].save('/tmp/foo')
size = os.stat('/tmp/foo').st_size

- 或 -

# save to memory, then check filesize
blob = request.files['file'].read()
size = len(blob)

我没有在官方文档中看到MAX_CONTENT_LENGTH,也没有像SO帖子那样手动检查文件大小。这两种方法最终是否相同,或者存在(大/微小?)差异?此外,patch_request_class是先将文件保存到磁盘以确定总上传大小,还是将其保存到内存中?

2 个答案:

答案 0 :(得分:1)

MAX_CONTENT_LENGTH是Flask本身的配置项,在0.6版中引入 http://flask.pocoo.org/docs/0.10/patterns/fileuploads/#improving-uploads

  

默认情况下,Flask会很乐意接受文件上传到无限制   内存量,但您可以通过设置来限制   MAX_CONTENT_LENGTH配置密钥:

from flask import Flask, Request

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
     

上面的代码会将允许的最大有效负载限制为16   兆字节。如果传输的文件较大,Flask会提出一个   RequestEntityTooLarge异常。

     

此功能已在Flask 0.6中添加,但可以在较旧版本中实现   版本以及通过子类化请求对象。更多   有关的信息请参阅档案中的Werkzeug文档   处理

来自flask-uploads来源: https://bitbucket.org/leafstorm/flask-uploads/src/440e06b851d24811d20f8e06a8eaf5c5bf58c241/flaskext/uploads.py?at=default

def patch_request_class(app, size=64 * 1024 * 1024):
    """
    By default, Flask will accept uploads to an arbitrary size. While Werkzeug
    switches uploads from memory to a temporary file when they hit 500 KiB,
    it's still possible for someone to overload your disk space with a
    gigantic file.

    This patches the app's request class's
    `~werkzeug.BaseRequest.max_content_length` attribute so that any upload
    larger than the given size is rejected with an HTTP error.

    .. note::

       In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
       setting, without patching the request class. To emulate this behavior,
       you can pass `None` as the size (you must pass it explicitly). That is
       the best way to call this function, as it won't break the Flask 0.6
       functionality if it exists.

    .. versionchanged:: 0.1.1

    :param app: The app to patch the request class of.
    :param size: The maximum size to accept, in bytes. The default is 64 MiB.
                 If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
                 setting will be used to patch.
    """
    if size is None:
        if isinstance(app.request_class.__dict__['max_content_length'],
                      property):
            return
        size = app.config.get('MAX_CONTENT_LENGTH')
    reqclass = app.request_class
    patched = type(reqclass.__name__, (reqclass,),
                   {'max_content_length': size})
    app.request_class = patched

所以我要说:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

答案 1 :(得分:1)

patch_request_class仅用于向后兼容。

从Flask 0.6开始,你应该使用app.config['MAX_CONTENT_LENGTH']

我最近接手了作为Flask-Uploads项目的维护者,我做的第一件事就是删除this commit中的patch_request_class,因为它什么也没做,只会给新项目增加混乱。任何依赖它的旧项目都应该只在Flask-Uploads==0.1.3文件中加requirements.txt