drzrzzkh462254 2017-11-02 09:29
浏览 99
已采纳

将PHP Curl查询转换为Python请求

I've been facing a few problems trying to convert the following PHP curl queries to Python requests.

Given PHP Code

$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)

My version of Python code

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)

Considering my request URLs are the same and so is the base 64 value for authorization. The PHP code returns the right response from the server but the Python one strangely says provides a response telling "code":"UNSUPPORTED_MEDIA_TYPE"

  • 写回答

1条回答 默认 最新

  • doudi1750 2017-11-03 05:04
    关注

    After some more checks, I seemed to figure out the issue was with the following lines, files needs mandatory filetype which can be obtained from MimeTypes().guess_type(path)[0] and the request_data should have been json.dumps(request_data)

    files = {'file': (temp_file_path, open(temp_file_path, 'rb'), filetype)}
    # .... Other code
    r = requests.post(url, files=files, data={'request': json.dumps(request_data)}, headers=headers)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵