我正在尝试测试获取文件列表的fastapi路由器。在html请求中,使用JS是可行的,但我需要测试它。我从fastapi使用TestClient,当我尝试发送列表时,我得到状态代码422,所以我去了哪个文档并尝试dict
,但我只得到了一个文件的列表
路由器
@router.post('/uploadone')
async def upload_file(response: Response,files:List = File(...)):
try:
properties = json.loads(files[len(files)-1])
check_file_type(files[:len(files)-1])
试验
def test_uploadone(self):
with open('upload_data/system_test/properties.json', 'rb') as file1:
json_file = json.load(file1)
with open('upload_data/system_test/heatmap1.csv', 'rb') as file:
body = file.read()
response = self.client.post('/actions/uploadone',
files={'files':('design_matrix1.csv', body),'json':
('prop.json', json.dumps(json_file))})
self.assertTrue(response.status_code == 200)
感谢您的帮助
我在测试上传文件列表时遇到了问题,我使用列表格式而不是dict 实现了它
files = [
("parameter", ("file1.txt", BytesIO(b"aaa"))),
("parameter", ("file2.txt", BytesIO(b"bbb"))),
]
response = self.test_client.post("/api/upload", files=files)
似乎还应该在files
中添加multipart/form-data
。
response=self.client.post('/actions/uploadone',files={'文件':('design_matrix1.csv',body,"多部分/表单数据"(,'json':('rop.json',json.dumps(json_file((}(
参见
https://www.semicolonworld.com/question/43327/how-to-send-a-ldquo-multipart-form-data-rdquo-with-requests-in-python
注意
我还建议您将数据和文件部分拆分为两个独立的字典,如上面链接的示例所示