ccd9c5b2a5cc9651698bf06770d8372d.png

感谢大神

顺川页​www.zhihu.com
451fce15f2eeb5f498670ecc9cd63819.png

的帮助,我才会上传任意多个文件。

现在我要写一个接口,需要同时上传几个文件(图像文件),同时也要传一些参数(设备ID和拍摄时间),服务器的代码好写,但客户端的代码就不容易传参。趟过的坑,记录一下。

服务器代码:

from typing import List
from fastapi import FastAPI,Form,UploadFile
app = FastAPI

@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...),deviceId:str=Form(...),shoottingTime:str=Form(...)):
    return {"filenames": [file.filename for file in files],"deviceId":deviceId,"shoottingTime":shoottingTime}

运行失败的客户端代码:

import requests
import json

url = "http://127.0.0.1:8000/uploadfiles/"

path_file0 = r'F:EbyProjectmy_super_projectsql_apptest_imagec3new_00004_1_0.jpg'
path_file1 = r'F:EbyProjectmy_super_projectsql_apptest_imagec3new_00004_1_1.jpg'
Path_files=[path_file0,path_file1]
files = []
for i in Path_files:
    files.append(('files',open(i,'rb')))

files.append(('deviceId',"123"))
files.append(('shoottingTime','2020-10-15 00:25:02'))

result = requests.post(url=url, files=files)
result_dict = json.loads(result.text)
print(result_dict)


##################################################
# 执行后的结果
{'detail': [{'loc': ['body', 'deviceId'], 'msg': 'str type expected', 'type': 'type_error.str'}, {'loc': ['body', 'shoottingTime'], 'm
sg': 'str type expected', 'type': 'type_error.str'}]}
####################################################
这意味着传参失败。

运行成功的客户端代码:

#更改两行代码即可
files.append(('deviceId',(None,"123")))
files.append(('shoottingTime',(None,'2020-10-15 00:25:02')))


###########################################################################
# 执行后的结果
{'filenames': ['new_00004_1_0.jpg', 'new_00004_1_1.jpg'], 'deviceId': '123', 'shoottingTime': '2020-10-15 00:25:02'}


FastAPI写接口很方便,就是写客户端代码不容易传递正确的参数。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐