gpt4 book ai didi

python - 测试 FastAPI 表单数据上传

转载 作者:行者123 更新时间:2023-12-05 09:08:21 24 4
gpt4 key购买 nike

我正在尝试使用 PythonFastAPI 测试文件及其元数据的上传。

这是我定义上传路径的方式:

@app.post("/upload_files")
async def creste_upload_files(uploaded_files: List[UploadFile], selectedModel: str = Form(...),
patientId: str = Form(...), patientSex: str = Form(...),
actualMedication: str = Form(...), imageDim: str = Form(...),
imageFormat: str = Form(...), dateOfScan: str = Form(...)):
for uploaded_dicom in uploaded_files:
upload_folder = "webapp/src/data/"
file_object = uploaded_dicom.file
#create empty file to copy the file_object to
upload_folder = open(os.path.join(upload_folder, uploaded_dicom.filename), 'wb+')
shutil.copyfileobj(file_object, upload_folder)
upload_folder.close()
return "hello"

(我没有使用元数据,但稍后会用到)。

我使用 unittest 进行测试:

class TestServer(unittest.TestCase):
def setUp(self):
self.client = TestClient(app)
self.metadata = {
"patientId": "1",
"patient_age": "M",
"patientSex": "59",
"patient_description": "test",
"actualeMedication": "test",
"dateOfScan": datetime.strftime(datetime.now(), "%d/%m/%Y"),
"selectedModel": "unet",
"imageDim": "h",
"imageFormat": "h"
}

def tearDown(self):
pass

def test_dcm_upload(self):
dicom_file = pydicom.read_file("tests/data/1-001.dcm")
bytes_data = dicom_file.PixelData

files = {"uploaded_files": ("dicom_file", bytes_data, "multipart/form-data")}
response = self.client.post(
"/upload_files",
json=self.metadata,
files=files
)
print(response.json())

但上传似乎不起作用,我得到了以下打印的响应:

{'detail': [{'loc': ['body', 'selectedModel'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'patientId'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'patientSex'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'actualMedication'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'imageDim'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'imageFormat'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'dateOfScan'], 'msg': 'field required', 'type': 'value_error.missing'}]}

我可能应该使用 Formdata 而不是正文请求 (json=self.metadata) 来上传,但我不知道应该如何完成。

最佳答案

答案只是将 json=self.metadata 替换为 data=self.metadata for a formData

关于python - 测试 FastAPI 表单数据上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63614660/

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