将cURL转为Python POST请求时遭遇414、400错误,求排查解决
问题:cURL POST转Python POST请求失败
要转换的cURL命令:
curl -X POST -F xls_file=@/path/to/form.xls https://api.ona.io/api/v1/forms
自己写的Python脚本:
with open(param_build_dir+'panther_test.xls', 'rb') as form: # xls = form.read() response = requests.post(ona_post_base_api, params={'xls_file': form}, headers = headers, auth=HTTPBasicAuth(username, password)) print(response.status_code) print(response.reason) print(response.text)
两种错误情况
- 取消注释
xls = form.read()时:
状态码:400
原因:Bad Request
响应文本:
{"type":"alert-error","text":"["XLSForm not provided, expecting either of these params: 'xml_file', 'xls_file', 'xls_url', 'csv_url', 'dropbox_xls_url', 'text_xls_form', 'floip_file"]"}
- 保留注释时:
状态码:414,Request-URI Too Large
解决方法
问题根源是两个错误用法:
- 用
params参数传递文件:params会把数据拼接到URL末尾,文件对象/内容转成字符串后会让URL异常冗长,触发414错误;且API要求的是multipart/form-data格式的文件上传,params完全不适用。 - 即使读取了文件内容,也没放到正确参数里,导致API识别不到
xls_file参数。
正确的Python脚本写法:
import requests from requests.auth import HTTPBasicAuth # 替换成你自己的变量值 param_build_dir = "/你的文件路径/" ona_post_base_api = "https://api.ona.io/api/v1/forms" username = "你的用户名" password = "你的密码" headers = {} # 不需要额外请求头可留空 with open(param_build_dir + 'panther_test.xls', 'rb') as form: # 构造files参数,对应curl的-F选项,指定参数名、文件名、文件对象和MIME类型 files = {'xls_file': ('panther_test.xls', form, 'application/vnd.ms-excel')} response = requests.post( ona_post_base_api, files=files, auth=HTTPBasicAuth(username, password), headers=headers ) print(response.status_code) print(response.reason) print(response.text)
说明:
files参数是requests专门处理multipart/form-data类型请求的选项,和curl的-F参数对应,是文件上传的正确方式。- 若不想手动指定MIME类型,可简化为
files={'xls_file': form},requests会自动尝试识别,但指定类型更稳妥。
内容的提问来源于stack exchange,提问作者alim1990
相关产品推荐
相关产品推荐

