【发布时间】:2017-11-02 09:29:58
【问题描述】:
我在尝试将以下 PHP curl 查询转换为 Python 请求时遇到了一些问题。
给定 PHP 代码
$cfile = new CURLFile($filePath,$fileType,$filename);
$request='{"signers":["abc@xyz.com"],"expire_in_days":10, "display_on_page":"all"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authorization: Basic Base64encode(client_id:client_secret)'));
$post = array('file'=>$cfile,'request' =>$request);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch)
我的 Python 代码版本
request_data = {}
request_data['signers'] = ['abc@xyz.com']
request_data['expire_in_days'] = 10
request_data['display_on_page'] = 'all'
temp_file_path = 'PdfTest.pdf'
files = {'file': open(temp_file_path, 'rb')}
headers = {}
headers['content-type'] = "multipart/form-data"
headers['authorization'] = 'Basic '+auth # auth contains b64 client:secret
r = requests.post(url, files=files, data={'request': request_data}, headers=headers)
考虑到我的请求 URL 和授权的 base 64 值相同。 PHP 代码从服务器返回正确的响应,但奇怪的是 Python 提供了一个响应告诉 "code":"UNSUPPORTED_MEDIA_TYPE"
【问题讨论】:
-
为什么选择将'content-type'设置为
multipart/form-data? -
API 文档提到在将数据发送到 API 时使用该内容类型。即使没有,我收到的错误仍然是一样的。
-
您是否尝试选择非 PDF 文件?好像是这个问题
-
是的,我也发送了同样错误的 TXT 文件。理想情况下,目标是发送 PDF 文件。
标签: php python curl python-requests