踩坑接口請求參數含文件
- requests
- 接口請求既有file,也有json。劃重點params
requests
官網地址
https://requests.readthedocs.io/en/stable/user/quickstart/#post-a-multipart-encoded-file
接口請求既有file,也有json。劃重點params
import requestsurl = "https://xx.xxxxx.com/api"# json類型的請求參數
payload = {'type': '123','doctype': '1'}
# 文件參數,注意files一定是列表啊,官網寫的字典不行!!!
# 比較優雅的寫的話,file最好用with open啊,自動colse。
# with open('xxx/xxx.docx', 'rb') as f:
# files = [
# ('file', ('xxx.docx',
# f,
# 'application/vnd.openxmlformats-#officedocument.wordprocessingml.document'))
# ]
files=[('file',('xxx.docx',open('/xxx/xxx/xxx/xxx.docx','rb'),'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))
]
# 請求頭類型-文件
headers = {'Content-Type': 'multipart/form-data',}# 重點是,用params傳json。如果用data就不行
response = requests.request("POST", url, headers=headers, params=payload, files=files)print(response.text)