[英]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.