使用Flask-Upload拒绝大于一定数量的文件? [英] Rejecting files greater than a certain amount with Flask-Uploads?

查看:115
本文介绍了使用Flask-Upload拒绝大于一定数量的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Flask recommends the Flask-Uploads module for handling uploads. I'd like to reject any file over a certain size. There are a few solutions floating around:

从文档中:

此外,您还可以使用patch_request_class对应用程序的request_class进行补丁,以具有最大的上传大小.

In addition, you can also use patch_request_class to patch your app’s request_class to have a maximum size for uploads.

patch_request_class(app, 32 * 1024 * 1024)

来自此SO帖子:

MAX_CONTENT_LENGTH是拒绝大于所需大小的文件上传的正确方法,

MAX_CONTENT_LENGTH is the correct way to reject file uploads larger than you want,

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 post那样手动检查文件大小.这两种方法最终是否相同,还是存在(大/细微?)差异?另外, patch_request_class 是先将文件保存到磁盘以确定总上传大小,还是保存到内存?

I don't see MAX_CONTENT_LENGTH mentioned in the official docs, nor does it even manually check the filesize like the SO post does. Are these two methods ultimately the same, or does there exist a (big/subtle?) difference? Also, does patch_request_class save the file to disk first to determine total upload size, or does it save to memory?

推荐答案

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

MAX_CONTENT_LENGTH is a configuration item for Flask itself, introduced in version 0.6 http://flask.pocoo.org/docs/0.10/patterns/fileuploads/#improving-uploads

默认情况下,Flask将愉快地接受文件上传到无限制内存量,但是您可以通过设置MAX_CONTENT_LENGTH配置键:

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

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

The code above will limited the maximum allowed payload to 16 megabytes. If a larger file is transmitted, Flask will raise an RequestEntityTooLarge exception.

此功能已在Flask 0.6中添加,但在较早版本中可以实现通过子类化请求对象来实现版本.欲了解更多有关信息,请查阅文件上的Werkzeug文档.处理.

This feature was added in Flask 0.6 but can be achieved in older versions as well by subclassing the request object. For more information on that consult the Werkzeug documentation on file handling.

并且从flask-uploads源中: https://bitbucket.org/leafstorm/flask-uploads/src/440e06b851d24811d20f8e06a8eaf5c5bf58c241/flaskext/uploads.py?at = default

And from the flask-uploads source: 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

这篇关于使用Flask-Upload拒绝大于一定数量的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆