【问题标题】:Translate PHP API POST call to Python using requests使用请求将 PHP API POST 调用转换为 Python
【发布时间】: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


【解决方案1】:

以下对我有用

files = {'receiptImage': open(RECEIPT_FOLDER+'/receipt.jpg', 'rb')}
resp = requests.post(process_endpoint, files=files)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2023-03-20
    • 2019-12-16
    • 2016-08-24
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多