繁体   English   中英

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

[英]Translate PHP API POST call to Python using requests

如何在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}

下面对我有用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM