How to do POST using requests module with Flask server?

Question:

I am having trouble uploading a file to my Flask server using the Requests module for Python.

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/Upload/'


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    <p>%s</p>
    """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

I am able to upload a file via web page, but I wanted to upload file with the requests module like this:

import requests
r = requests.post('http://127.0.0.1:5000', files={'random.txt': open('random.txt', 'rb')})

It keeps returning 400 and saying that “The browser (or proxy) sent a request that this server could not understand”

I feel like I am missing something simple, but I cannot figure it out.

Asked By: Duggy

||

Answers:

You upload the file as the random.txt field:

files={'random.txt': open('random.txt', 'rb')}
#      ^^^^^^^^^^^^ this is the field name

but look for a field named file instead:

file = request.files['file']
#                    ^^^^^^ the field name

Make those two match; using file for the files dictionary, for example:

files={'file': open('random.txt', 'rb')}

Note that requests will automatically detect the filename for that open fileobject and include it in the part headers.

Answered By: Martijn Pieters

Because you have <input> with name=file so you need

 files={'file': ('random.txt', open('random.txt', 'rb'))}

Examples in requests doc: POST a Multipart-Encoded File

Answered By: furas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.