How to do POST using requests module with Flask server?
<p>I am having trouble uploading a file to my Flask server using the Requests module for Python. </p>

<pre><code>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 """
    &lt;!doctype html&gt;
    &lt;title&gt;Upload new File&lt;/title&gt;
    &lt;h1&gt;Upload new File&lt;/h1&gt;
    &lt;form action="" method=post enctype=multipart/form-data&gt;
      &lt;p&gt;&lt;input type=file name=file&gt;
         &lt;input type=submit value=Upload&gt;
    &lt;/form&gt;
    &lt;p&gt;%s&lt;/p&gt;
    """ % "&lt;br&gt;".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
</code></pre>

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

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

<p>It keeps returning 400 and saying that "The browser (or proxy) sent a request that this server could not understand"</p>

<p>I feel like I am missing something simple, but I cannot figure it out.</p>

<p>You upload the file as the <code>random.txt</code> field:</p>

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

<p>but look for a field named <code>file</code> instead:</p>

<pre><code>file = request.files['file']
#                    ^^^^^^ the field name
</code></pre>

<p>Make those two match; using <code>file</code> for the <code>files</code> dictionary, for example:</p>

<pre><code>files={'file': open('random.txt', 'rb')}
</code></pre>

<p>Note that <code>requests</code> will automatically detect the filename for that open fileobject and include it in the part headers.</p>

python post flask python-requests