【问题标题】:is there a way to send multiple images to an API at the same time fastapi有没有办法同时将多个图像发送到 API fastapi
【发布时间】:2021-01-25 03:36:56
【问题描述】:

我需要用多张图片点击 fastapi

@app.post("/text")
def get_text(files: List[UploadFile] = File(...)):

当我尝试使用 /docs 界面上传多张图片时它工作正常,我尝试使用一个文件它工作正常这里是它的代码

import requests
import json
def get_text(image_path):
    #images={}
    url = 'http://address/text'
    try:
        with open(image_path, "rb") as im:
            image_data={"files":im}
            response=requests.post(url,files=image_data)
            return json.loads(response.text)
    except Exception as er:
        print("error occured")
        return "{} error occured".format(er)

当我尝试向 image_data 添加更多图像但出现错误时。

image_data ={"files":[]}
for image in image_list:
    with open(image, "rb") as im:
        image_data['files'].append(im)

上面的代码试过了,没用。

上面运行后的错误信息 error message

【问题讨论】:

    标签: python-3.x rest dictionary python-requests fastapi


    【解决方案1】:

    终于找到解决办法了,不是fastapi的问题,和requests库有关

    如果有人需要这里的解决方案

    files = [
            ('files', ('image1', open('/Users/ai/image1.jpg','rb'), 'image/png')),
            ('files', ('image2', open('/Users/ai/image2.jpeg','rb'), 'image/png'))
            ]
    

    您可以对多个文件使用以下函数

    import requests
    import json
    
    def get_text(image_list,url):
        try:
            image_data=[]
            for image in image_list:
                image_data.append(('files',(image.split('/')[-1],open(image,'rb'),'image/png')))#('files',(image_name,open image,type))
            response=requests.post(url,files=image_data)
            return json.loads(response.text)
        except Exception as er:
            print("error occured")
            return "{} error occured".format(er)
    

    您可以查看文档Here

    谢谢..!

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2022-01-16
      相关资源
      最近更新 更多