python - API、Python、请求未收到 POST pdf 文件

标签 python flask python-requests

所以我构建了一个 API,它接收 pdf 文件和 json 并将文件转换为文本。使用 Postman 进行测试效果很好,但是现在我尝试编写一个脚本来发送多个图像,但 API 没有收到我在脚本中发送的图像。它接收请求但不接收其内容。另外,我也没有得到 json 文件,尽管它确实显示在脚本端。

我查看了 Postman 请求并在脚本中实现了它,但它仍然不起作用。我尝试仅发送不带 json 的文件,但无法使其正常工作。我一直在查看 Flask 和 request 的文档,但找不到它没有收到图像的解释。

#Script code
import requests
import time
import glob

url = "http://127.0.0.1:5000/transcribe"
for file in glob.glob("/Receipts_to_scan/*.pdf"):

    print(open(file, "rb"))

    files = {
        'file': open(file, 'rb'),
        'json': '{"method":"sypht"}'
    }

    headers = {
        'Accept': "application/pdf",
        'content-type': "multipart/form-data",
        'Connection': 'keep-alive'
    }

    response_decoded_json = requests.post(url, files=files, headers=headers)
    time.sleep(5)
    print(response_decoded_json)

#--------------------------
#API code
from flask import Flask, request
@app.route("/transcribe", methods = ["POST"])
def post():
    #Getting the JSON data with all the settings in it
    json_data = request.files["json"]
    print(json_data)
    image = request.files["file"]
    print(image)

最佳答案

您可以尝试以下操作吗?这样您就可以在请求中组合文件和其他数据(例如字典)。

更改您的 Flask API:

#Getting the JSON data with all the settings in it
json_data = request.form    # <--- change this line
print(json_data)

然后发出这样的请求(无需手动设置 header ):

files = {
    'file': (file, open(file, 'rb'), "application/pdf")
}

data = {
    "method": "sypht"
}

response_decoded_json = requests.post(url, files=files, data=data)
time.sleep(5)
print(response_decoded_json)

这应该会给你一个 ImmutableMultiDict和一个FileStorage一起工作的对象。

然后您的 API 会打印:

ImmutableMultiDict([('method', 'sypht')])

<FileStorage: 'test.pdf' ('application/pdf')>

关于python - API、Python、请求未收到 POST pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409431/

相关文章:

python - 使用 PyInstaller (--onefile) 捆绑数据文件

python - 数组与整数

python - 如何将列表转换为字符串

python - 网页抓取 - 不显示内容

python - Python请求中 `data`和 `files`的区别

f(a, *b) 的 Python 参数匹配

python - Heroku 本地失败,没有错误消息

python - 在 Flask-Login token_loader 中加载 token 引发 "BadTimeSignature: timestamp missing"

python - 如果与线程 Flask 应用程序一起运行,grpc 服务器会立即退出

在 macOS Sierra 上使用 OpenSSL 的 python 请求