首页 > 解决方案 > 创建一个最小的烧瓶/请求文件上传器

问题描述

我正在尝试创建一个最小的烧瓶服务器/客户端 python 电影文件上传器,但我的客户端代码似乎无法正常工作,我想知道我是否需要比我拥有的更多?

服务器.py

from flask import Flask, request
app = Flask(__name__)

@app.route('/',  methods=['GET', 'POST', 'PUT'])
def hello_world():
    file = request.files
    return(str(file))

运行方式:烧瓶运行

上传者.py

import requests

files = {'file': open("BigBuckBunny_320x180.mp4")}
r = requests.post("http://127.0.0.1:5000/", files)
print(r.text)

运行为:python Uploader.py

但是该hello_world方法返回ImmutableMultiDict([])

出于调试目的,我使用了以下似乎可行的 curl 片段:

curl -i -X PUT  -F filedata=@BigBuckBunny_320x180.mp4 "http://localhost:5000/"

并返回

ImmutableMultiDict([('file', <FileStorage: u'BigBuckBunny_320x180.mp4' ('application/octet-stream')>)])

任何想法为什么Uploader.py失败?

标签: pythonflask

解决方案


我尝试了你给我们的例子,我想我设法找到了解决方案。

经过一番挖掘,我发现您可以使用模块流式传输请求:requests

Requests 支持流式上传,允许您发送大型流或文件而无需将它们读入内存。

您只需要提供一个要流式传输的文件并以读取二进制模式打开它,rb.

应用程序.py

from flask import Flask, request
app = Flask(__name__)


@app.route('/',  methods=['GET', 'POST', 'PUT'])
def hello_world():
    # 'bw' is write binary mode
    with open("BigBuckBunny_320x180_flask_upload.mp4", "bw") as f:
        chunk_size = 4096
        while True:
            chunk = request.stream.read(chunk_size)
            if len(chunk) == 0:
                return 'Done'

            f.write(chunk)


if __name__ == '__main__':
    app.run()

上传者.py

import requests

# Give proper path to your file, I used mine from flask app directory
with open('BigBuckBunny_320x180.mp4', 'rb') as f:
    requests.post('http://127.0.0.1:5000/', data=f)

检查这篇文章。


推荐阅读