使用瓶子(或Flask或类似物品)上传流文件

2024-05-15 06:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个REST前端使用Python/Bottle编写,它处理文件上传,通常是大型文件。API是这样的:

客户端以文件作为负载发送PUT。除此之外,它还发送日期和授权头。这是一种防止重播攻击的安全措施——使用目标url、日期和其他一些东西,用一个临时密钥对请求进行签名

现在问题来了。如果提供的日期在15分钟的给定日期时间窗口中,则服务器接受该请求。如果上传需要足够长的时间,它将长于允许的时间增量。现在,请求授权处理是使用decoratoronbottleview方法完成的。但是,除非上传完成,否则bottle不会启动分派过程,因此验证在较长的上传上失败。

我的问题是:有没有办法向bottle或WSGI解释如何立即处理请求并在上传过程中进行流式传输?出于其他原因,这对我也很有用。或者其他解决办法?在我写这篇文章的时候,我想到了WSGI中间件,但是,我还是希望获得外部的洞察力。

我愿意切换到Flask,甚至其他Python框架,因为剩下的前端相当轻量级。

谢谢你


Tags: 文件服务器restapiurl客户端wsgibottle
2条回答

我建议在前端将传入的文件分成较小的块。我这样做是为了在Flask应用程序中实现大文件上传的暂停/恢复功能。

使用Sebastian Tschan's jquery plugin,可以通过在初始化插件时指定maxChunkSize来实现分块,如下所示:

$('#file-select').fileupload({
    url: '/uploads/',
    sequentialUploads: true,
    done: function (e, data) {
        console.log("uploaded: " + data.files[0].name)
    },
    maxChunkSize: 1000000 // 1 MB
});

现在,当上传大文件时,客户端将发送多个请求。您的服务器端代码可以使用Content-Range头将原始大文件修补回一起。对于烧瓶应用程序,视图可能类似于:

# Upload files
@app.route('/uploads/', methods=['POST'])
def results():

    files = request.files

    # assuming only one file is passed in the request
    key = files.keys()[0]
    value = files[key] # this is a Werkzeug FileStorage object
    filename = value.filename

    if 'Content-Range' in request.headers:
        # extract starting byte from Content-Range header string
        range_str = request.headers['Content-Range']
        start_bytes = int(range_str.split(' ')[1].split('-')[0])

        # append chunk to the file on disk, or create new
        with open(filename, 'a') as f:
            f.seek(start_bytes)
            f.write(value.stream.read())

    else:
        # this is not a chunked request, so just save the whole file
        value.save(filename)

    # send response with appropriate mime type header
    return jsonify({"name": value.filename,
                    "size": os.path.getsize(filename),
                    "url": 'uploads/' + value.filename,
                    "thumbnail_url": None,
                    "delete_url": None,
                    "delete_type": None,})

对于您的特定应用程序,您只需确保每个请求仍然发送正确的身份验证头。

希望这有帮助!我在这个问题上挣扎了一段时间;)

当使用plupload解决方案时可能是这样的:

$("#uploader").plupload({
    // General settings
    runtimes : 'html5,flash,silverlight,html4',
    url : "/uploads/",

    // Maximum file size
    max_file_size : '20mb',

    chunk_size: '128kb',

    // Specify what files to browse for
    filters : [
        {title : "Image files", extensions : "jpg,gif,png"},
    ],

    // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
    dragdrop: true,

    // Views to activate
    views: {
        list: true,
        thumbs: true, // Show thumbs
        active: 'thumbs'
    },

    // Flash settings
    flash_swf_url : '/static/js/plupload-2.1.2/js/plupload/js/Moxie.swf',

    // Silverlight settings
    silverlight_xap_url : '/static/js/plupload-2.1.2/js/plupload/js/Moxie.xap'
});

在这种情况下,flask python代码类似于:

from werkzeug import secure_filename

# Upload files
@app.route('/uploads/', methods=['POST'])
def results():
    content = request.files['file'].read()
    filename = secure_filename(request.values['name'])

    with open(filename, 'ab+') as fp:
        fp.write(content)

    # send response with appropriate mime type header
    return jsonify({
        "name": filename,
        "size": os.path.getsize(filename),
        "url": 'uploads/' + filename,})

Plupload总是以完全相同的顺序发送数据块,从第一个到最后一个,所以您不必费心于seek或类似的东西。

相关问题 更多 >

    热门问题