0

I was trying to create a minimal flask server/client python movie file uploader but my client-code doesn't seem to be working properly and I'm wondering if I need more then what I have?

Server.py

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

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

running as: flask run

Uploader.py

import requests

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

running as: python Uploader.py

However the hello_world method returns ImmutableMultiDict([])

For Debugging purposes I've used this following curl snippet which seems to work:

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

and returns

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

Any Idea why the Uploader.py fails?

user1767754
  • 23,311
  • 18
  • 141
  • 164

1 Answers1

0

I tried example you gave us and I think I managed to find a solution.

After some digging, I found that you can stream requests with requests module:

Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory.

You just need to provide a file to be streamed and open it in read binary mode, rb.

app.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()

Uploader.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)

Check this article.

Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57