簡體   English   中英

測試 FastAPI 表單數據上傳

[英]Testing FastAPI FormData Upload

我正在嘗試使用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 替換可用於 body 參數的json=self.metadata self.metadata

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM