簡體   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