gpt4 book ai didi

python - 我需要通过 FastAPI 发送文件和数据。我正在尝试发送请求但无法正常工作

转载 作者:行者123 更新时间:2023-12-02 01:57:41 28 4
gpt4 key购买 nike

我需要通过 FastAPI 发送文件和数据。我正在尝试发送请求,但无法正常工作

例如:

服务器:

import uvicorn
from fastapi import FastAPI, File
from pydantic import BaseModel


app = FastAPI()


class Data(BaseModel):
test1: str = None
test2: str = None
test3: str = None


@app.post("/uploadfile/")
async def create_file(
data: Data,
image: bytes = File(...),
):
return {"postdata": len(image),
"data": data.camera,
}

if __name__ == "__main__":
uvicorn.run(app)

客户:

import requests
import cv2
import json
image = cv2.imread('/marti.jpg')
data2 = cv2.imencode(".jpg", image)[1]


payload = {"test1": "value_1", "test2": "value_2", "test3": "value_3"}
files = {
'image': ('a.jpg', data2.tobytes(), 'image/jpeg', {'Expires': '0'})
}

res = requests.post("http://localhost:8000/uploadfile/",
files=files, data=payload)
print(res.content)
print(res.status_code, res.json())

我得到的错误:

422 Unprocessable Entity

  • 如果我从请求中删除"file",它就可以工作。
  • 如果我从请求中删除“数据”,它就会起作用。

面对这种情况,您有什么建议?

最佳答案

你不能。请参阅文档 here :

You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

This is not a limitation of FastAPI, it's part of the HTTP protocol.

这通常是通过期待 Form 而不是 json 来解决(参见这个答案 here ),或者通过两个独立的端点来解决;一个上传照片并返回匹配 ID,另一个利用该 ID 将 json 数据发送到。

关于python - 我需要通过 FastAPI 发送文件和数据。我正在尝试发送请求但无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69413005/

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