如何multipart/form-data在python中发送请求?如何发送文件,我理解,但如何通过这种方法发送表单数据无法理解.
我根据官方文档使用fastapi上传文件,就像:
@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
file2store = await file.read()
# some code to store the BytesIO(file2store) to the other database
Run Code Online (Sandbox Code Playgroud)
当我使用 python requests lib 发送请求时:
f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)
Run Code Online (Sandbox Code Playgroud)
file2store 始终为空。有时(很少见),它可以获取文件字节,但几乎所有时间都是空的,所以我无法在另一个数据库上恢复文件。我还尝试了 'bytes' 而不是 'UploadFile',我得到了相同的结果。我的代码有什么地方不对,还是我使用fastapi上传文件的方式有问题?我google了很长时间,但没有成功。所以我在这里提出问题,希望知道答案的人可以帮助我。谢谢
这是我尝试上传图像列表的代码:
import requests
import glob
import cv2
path = glob.glob("test_folder/*", recursive=True) # a list of image's path
lst_img = []
for p in path[:3]:
# img = cv2.imread(p)
lst_img.append((p, open(p, 'rb'), "image/jpeg"))
data = {"files": lst_img}
url = "http://localhost:6789/" # url api of app
res = requests.post(url=url, data=data)
print(res.status_code)
print(res.text)
Run Code Online (Sandbox Code Playgroud)
我正在尝试通过 Python 请求(包)将图像列表上传到 FastAPI 端点,但也许我的请求格式错误,导致错误422:
import requests
import glob
import cv2
path = glob.glob("test_folder/*", recursive=True) # a list of image's path
lst_img = []
for p …Run Code Online (Sandbox Code Playgroud)