如何在FastAPI中接收图像和json数据?

Daw*_*y33 2 python api fastapi

我通过以下方式将图像和 json 数据发送到我的 API:

import requests
filename = "test_image.jpeg"
files = {'my_file': (filename, open(filename, 'rb'))}
json={'first': "Hello", 'second': "World"}

response = requests.post('http://127.0.0.1:8000/file', files=files, params=json)
Run Code Online (Sandbox Code Playgroud)

如何通过FastAPI在服务器端同时接收图像和json数据?

我的代码如下所示:

@app.post('/file')
def _file_upload(my_file: UploadFile = File(...), params: str = Form(...)):

    image_bytes = my_file.file.read()
    decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
    pg_image = cv2.resize(decoded, (220, 220))
    return {"file_size": params}
Run Code Online (Sandbox Code Playgroud)

但是,这给了我以下错误:

<Response [422]>
{'detail': [{'loc': ['body', 'params'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么吗?

JPG*_*JPG 5

您必须将路由器函数中期望的参数定义为:

# app.py
from fastapi import FastAPI, File, UploadFile, Form

app = FastAPI()


@app.post('/file')
def _file_upload(
        my_file: UploadFile = File(...),
        first: str = Form(...),
        second: str = Form("default value  for second"),
):
    return {
        "name": my_file.filename,
        "first": first,
        "second": second
    }
Run Code Online (Sandbox Code Playgroud)
# client.py
import requests

filename = "requirements.txt"
files = {'my_file': (filename, open(filename, 'rb'))}
json = {'first': "Hello", 'second': "World"}

response = requests.post(
    'http://127.0.0.1:8000/file',
    files=files,
    data={'first': "Hello", 'second': "World"}
)
print(response.json())
Run Code Online (Sandbox Code Playgroud)