5

I am trying to upload a file from my desktop to Flask running on my local machine without using a web form at all. I have looked at the examples for BOTH Python Requests and Poster.

Here is the code for my Flask API

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

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/upload', methods= ['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['files']
        f.save('/Users/djangod/newTest.txt')
        return '200'
    else:
        return 'Upload Page'

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

Here is the code from my Python script using Requests

import requests

url = "http://127.0.0.1:5000/upload"
files = {'file': open('/Users/djangod/text.txt', 'rb')}
r = requests.post(url, files=files)

I get an error 400 and cannot figure out why but for some strange reason running this curl command works

curl -i -X POST -F [email protected] http://127.0.0.1:5000/upload

I initially thought Flask was configured incorrectly, until curl worked. I am running on OS X 10.8.5 and using virtualenv. Any help would be greatly appreciated. Thanks in advance.

1 Answer 1

8

Your requests code is wrong (probably a typo). Below is what's different between what should work and what you have:

files = {'files': open('/Users/djangod/text.txt', 'rb')}
#             ^ missing an s

You're telling Flask to look for a file called 'files' so you need to tell requests to send that as the filename.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! I knew it was something stupid on my part. That'll teach me to code and watch college football at the same time.
Update: The typo actually exists in Requests official documentation. I just copied and pasted it :(
No worries. Submit a pull request and add yourself to the AUTHORS.rst. We merge documentation PRs ASAP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.