如何使用带有 Flask 服务器的请求模块进行 POST?

Dug*_*ggy 1 python post flask python-requests

我在使用 Python 的请求模块将文件上传到 Flask 服务器时遇到问题。

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)
Run Code Online (Sandbox Code Playgroud)

我可以通过网页上传文件,但我想用这样的请求模块上传文件:

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

它不断返回 400 并说“浏览器(或代理)发送了此服务器无法理解的请求”

我觉得我错过了一些简单的东西,但我无法弄清楚。

Mar*_*ers 5

您将文件上传为random.txt字段:

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

但寻找一个名为的字段file

file = request.files['file']
#                    ^^^^^^ the field name
Run Code Online (Sandbox Code Playgroud)

使这两个匹配;使用filefiles词典,例如:

files={'file': open('random.txt', 'rb')}
Run Code Online (Sandbox Code Playgroud)

请注意,requests它将自动检测该打开文件对象的文件名并将其包含在部分标题中。


fur*_*ras 5

因为你必须<input>name=file,所以你需要

 files={'file': ('random.txt', open('random.txt', 'rb'))}
Run Code Online (Sandbox Code Playgroud)

请求文档中的示例:POST a Multipart-Encoded File