【发布时间】:2019-07-27 23:37:26
【问题描述】:
我怎样才能在 Python 中发出以下 PHP API 端点发布请求:
$cSession = curl_init();
$cFile = curl_file_create('my_receipt.jpg'); //Path to the file which will be uploaded
$post = array('file_contents' => $cFile);
curl_setopt($cSession, CURLOPT_URL, 'https://api.tabscanner.com/{your_api_key}/process');
curl_setopt($cSession, CURLOPT_POST, 1);
curl_setopt($cSession, CURLOPT_POSTFIELDS, $post);
curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cSession, CURLOPT_HEADER, false);
$result = curl_exec($cSession);
if (curl_errno($cSession)) {
$result = curl_error($cSession);
}
curl_close($cSession);
echo $result;
我尝试了以下方法:
import requests as rq
import json
import os
api_key = 'xxxx'
url = 'https://api.tabscanner.com/{}/process'.format(api_key)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) + '/'
img = PROJECT_ROOT + 'receipt1.jpg' # I presume this needs to be read as an image file, rather than just the filename
result = rq.post(url, data=json.dumps({'file': img}))
print(result.text)
这会导致以下输出:
{"message":"ERROR_FORM_PARSER: Error: missing content-type header","status":"failed","status_code":4,"success":false,"code":406}
【问题讨论】:
-
您错过了内容类型标题。 Docs
-
我如何将它添加到
requests.post调用中? PHP示例还指定CURLOPT_HEADER为false,所以我认为它不接受标题。 -
@KlausD。我已经尝试过
rq.post(url, headers={'file': img})、rq.post(url, data=json.dumps({'file': img}), headers={})、rq.post(url, data=json.dumps({'file': img}), headers=False)等。这些都不起作用。 -
您真的应该阅读错误消息和我链接的文档。
-
我有并且无论我尝试为
headers参数包含什么,我都会遇到与我原来的问题相同的错误。我什至查看了requests源代码,看看我是否错误地添加了标题。
标签: php python api post python-requests