我使用FastAPI接收图像,方法如下:
import cv2 import numpy as np from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post('/file') def _file_upload(my_file: UploadFile = File(...)): image_bytes = my_file.file.read() decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1) return {"file_size": my_file.filename}
现在,如果我想把json负载和图像一起发送,我该怎么做?
例子:
import requests filename = "test_image.jpeg" files = {'my_file': (filename, open(filename, 'rb')), 'some_other_data': 'hello'} response = requests.post('http://127.0.0.1:8000/file', files=files) print(response.json())
some_other_data ?
some_other_data
您正在发送一个如下所示的请求
files = { 'my_file': (filename, open(filename, 'rb')), 'some_other_data': 'hello' }
端点需要两个参数 my_file some_other_data ,自从 一些其他数据 是一个 str
my_file
一些其他数据
str
from fastapi import FastAPI, File, UploadFile, Body @app.post('/file') def my_endpoint(my_file: UploadFile = File(...), some_other_data: str = Body(...)): ...