[英]CMD Curl equivalent in PHP - python script flask
我通過我的 CMD 打電話給 python api。
@app.route("/getResult", methods = ['GET', 'POST'])
def funcName():
print("Fetching the passed input file")
f = request.files['data']
print("Reading the file using pandas")
data = pd.read_csv(f)
這就是我在 cmd 中調用它的方式,它只返回一個數字 output。
curl -F data=@location\data_sample.csv localhost:5000/getResult
我正在嘗試使用以下代碼通過 php 調用它。
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $uri);
$postData = array(
'data' => '@'.$file_path,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
print_r($response);die();
我收到此錯誤:
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError:400 錯誤請求:瀏覽器(或代理)發送了此服務器無法理解的請求。 鍵錯誤:“數據”
至於我,你只發送字符串@location\data_sample.csv
因為命令@
可能只在真正的curl
中有效。
根據 PHP 文檔,您應該使用CURLFile或curl_file_create
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $uri);
// Create a CURLFile object
$cfile = curl_file_create('location/data_sample.csv', 'text/csv', 'data_sample.csv');
// Assign POST data
$data = array('data' => $cfile);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
print_r($response);die();
編輯:
我用來測試它的完整代碼。
主文件
from flask import Flask
import pandas as pd
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
print("Fetching the passed input file")
f = request.files['data']
print("Reading the file using pandas")
data = pd.read_csv(f)
print("Send back as HTML with table")
return data.to_html()
if __name__ == '__main__':
#app.debug = True
app.run() #debug=True
main.php
<?php
$uri = 'http://127.0.0.1:5000/';
$file_path = 'location/data_sample.csv';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $uri);
//$postData = array('data' => '@'.$file_path); // doesn't work
// Create a CURLFile object
$cfile = curl_file_create($file_path, 'text/csv', 'data_sample.csv');
//$cfile = new CURLFile($file_path, 'text/csv', 'data_sample.csv');
// Assign POST data
$postData = array('data' => $cfile);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
print_r($response);
die();
?>
在Linux Mint 20
、 PHP 7.4.3
、 Python 3.8.5
上測試。
我不得不在'location/data_sample.csv'
中使用/
而不是\
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.