首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >API、Python、请求未收到POST pdf-file

API、Python、请求未收到POST pdf-file
EN

Stack Overflow用户
提问于 2019-08-08 17:31:45
回答 1查看 1.8K关注 0票数 3

因此,我构建了一个API,它接受pdf文件和json,并将文件转换为文本。使用Postman测试可以很好地工作,但是现在我尝试创建一个脚本来发送多个图像,但API无法接收到我在脚本中发送的图像。它接收请求,但不接收其内容。另外,我也没有得到json文件,而它确实显示在脚本端。

我查看了Postman请求并在脚本中实现了它,但是它仍然不起作用。我尝试只发送没有json的文件,但无法使其正常工作。我一直在查找flask和request的文档,但我找不到为什么它没有收到图像的原因。

代码语言:javascript
复制
#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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-08 19:41:25

你可以试试下面的方法吗?通过这种方式,您可以在请求中组合文件和其他数据(如字典)。

更改Flask API:

代码语言:javascript
复制
#Getting the JSON data with all the settings in it
json_data = request.form    # <--- change this line
print(json_data)

然后发出如下请求(无需手动设置headers):

代码语言:javascript
复制
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将打印:

代码语言:javascript
复制
ImmutableMultiDict([('method', 'sypht')])

<FileStorage: 'test.pdf' ('application/pdf')>
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57409431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档