gpt4 book ai didi

python - 如何从 FastAPI 端点返回字典 + 图像?

转载 作者:行者123 更新时间:2023-12-01 00:09:05 25 4
gpt4 key购买 nike

我正在尝试使用 FastAPI 来允许我的(dockerized)服务器响应返回的 API 调用

  • 图像图像,以及
  • 字典additional_dict

(对于机器学习示例,这可以是来自分类器和显着性图的分类标签)。

就我而言,我认为使用相同的端点来获取两个对象是有意义的,因为它们是通过相同的计算生成的。

我可以使用类似 https://stackoverflow.com/a/55905051/4240413 的内容成功地将图像返回为二进制图像:

from PIL import Image
from fastapi import FastAPI, File
import tempfile
from starlette.responses import FileResponse

@app.post("/getstuff")
async def get_image_and_data(file: bytes = File(...)):

image, additional_dict = process_image(image)

with tempfile.NamedTemporaryFile(mode="w+b", suffix=".png", delete=False) as outfile:
image.save(outfile)
return FileResponse(outfile.name, media_type="image/png")

当我通过 localhost:8000/docs 上的 swagger UI 调用服务时,这甚至可以让我看到图像响应。

但是,我不知道如何将图像二进制和字典放在一起。

我尝试用以下内容替换我的返回语句:

return FileResponse(outfile.name, media_type="image/png"), additional_dict

但这并没有真正起作用(当在 localhost:8000/docs 上尝试 swagger 时,我只是得到下面的 json 回复,其中包含创建的临时文件的路径)

[{
"path": "/tmp/tmpldwe_79d.png",
"status_code": 200,
"filename": null,
"send_header_only": false,
"media_type": "image/png",
"background": null,
"raw_headers": [
[
"content-type",
"image/png"
]
],
"stat_result": null
},
{
"foo": 1,
"bar": 2
}]

是否可以从同一端点获取二进制图像和附加字典的响应?如果是这样,最好的方法是什么?
是否可以在 Swagger UI /docs 中渲染图像并读取其中的字典值?

最佳答案

您可以使用 base64 对二进制数据(在您的情况下为图像)进行编码,并通过字典发送编码后的字符串。

   import base64

with open("image.png", "rb") as image_file:
encoded_image_string = base64.b64encode(image_file.read())

payload = {
"mime" : "image/png",
"image": encoded_image_string,
"some_other_data": None
}

因此该字典将包含 base64 编码的图像和任何其他数据字段。

在前端,您可以将图像从 Base64 字符串解码回字节并将其呈现给用户。

关于python - 如何从 FastAPI 端点返回字典 + 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com