如何在fastapi的一个响应中返回图像和json ?



我得到一个图像,改变它,然后使用神经网络进行分类,应该返回一个新的图像和json响应。用一个端点怎么做呢?图像返回流响应,但如何添加json到它?

import io
from starlette.responses import StreamingResponse
app = FastAPI()
@app.post("/predict")
def predict(file: UploadFile = File(...)):
img = file.read()
new_image = prepare_image(img)
result = predict(new_image)
return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

我在响应头中添加了json。改变:

@app.post("/predict")
def predict(file: UploadFile = File(...)):
img = file.read()
new_image = prepare_image(img)
result = predict(new_image)
return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

@app.post("/predict/")
def predict(file: UploadFile = File(...)):
file_bytes = file.file.read()
image = Image.open(io.BytesIO(file_bytes))
new_image = prepare_image(image)
result = predict(image)
bytes_image = io.BytesIO()
new_image.save(bytes_image, format='PNG')
return Response(content = bytes_image.getvalue(), headers = result, media_type="image/png")

我有同样的问题,虽然,我的文件存储在本地,但我仍然必须返回JSON,和图像在一个单一的响应。

这个很适合我,更简洁,更短:

@app.post("/ImgAndJSON")
# Postmsg is a Pydantic model having 1 str field
def ImgAndJSON(message:PostMsg):
results={"message":"This is just test message"}
return FileResponse('path/to/file.png',headers=results)

最新更新