Python Requests如何为FastAPI多文件上传接口构造列表格式上传请求
前置依赖确认
先确保你已经安装了multipart相关依赖:
pip install python-multipart
错误原因&修复方案
你碰到的报错由几个核心问题导致:
- requests多文件传参格式错误:requests的
files参数不支持直接把文件元组列表作为字典单个键的值,会触发类型解析错误 - 参数名&请求路径不匹配:FastAPI接口定义的接收字段是
files、路由是带尾部斜杠的/uploadfiles/,你的测试代码里字段用了uploads、请求路径少了尾部斜杠 - 同一文件句柄重复使用:单个打开的文件句柄读取一次后指针会落在文件末尾,第二次读取会返回空内容
修复后的测试代码
import requests testapi = '' # 替换为你的接口地址,比如http://127.0.0.1:8000 # 分别打开两个文件,不要复用同一个文件句柄 with open("profile.jpeg", "rb") as f1, open("profile2.jpeg", "rb") as f2: response = requests.post( # 路径补全尾部斜杠,和接口定义一致 f"{testapi}/uploadfiles/", # files参数直接传列表,每个元素第一个值为接口接收的字段名files files=[ ("files", ("profile.jpeg", f1, "image/jpeg")), ("files", ("profile2.jpeg", f2, "image/jpeg")), ] ) print(response.json()) assert response.status_code == 200
如果你只有一个测试文件要模拟两次上传,可以在第一次读取后把文件指针重置到开头:
import requests testapi = '' with open("profile.jpeg", "rb") as image_file: response = requests.post( f"{testapi}/uploadfiles/", files=[ ("files", ("profile.jpeg", image_file, "image/jpeg")), ] ) # 重置文件指针到开头 image_file.seek(0) response2 = requests.post( f"{testapi}/uploadfiles/", files=[ ("files", ("profile2.jpeg", image_file, "image/jpeg")), ] )
内容的提问来源于stack exchange,提问作者Edison
相关产品推荐
相关产品推荐

