如何解决测试FastAPI FormData上传
我正在尝试使用 Python 和 FastAPI 测试文件及其元数据的上传。
这是我定义上传路线的方式:
@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'],'patientSex'],'actualMedication'],'imageDim'],'imageFormat'],'dateOfScan'],'type': 'value_error.missing'}]}
我可能应该使用Formdata而不是正文请求(json=self.metadata
)进行上传,但是我不知道应该怎么做。
解决方法
答案只是将json=self.metadata
替换为data=self.metadata
即可用于formData的stringA:stringB:A1B2C3D4.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。