django-d
django-d

Reputation: 2280

Python script that uploads a file without using a form and just uses Flask as API

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.

Upvotes: 5

Views: 6023

Answers (1)

Ian Stapleton Cordasco
Ian Stapleton Cordasco

Reputation: 28747

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.

Upvotes: 8

Related Questions