使用请求将PHP-API POST调用转换为Python

2024-10-01 22:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中发出以下PHP API端点post请求:

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


Tags: thetokeyimportapiosresultcurl

热门问题