I'm calling a python api via my CMD.
@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)
This is how i call it in cmd and it returns just a number output.
curl -F data=@location\data_sample.csv localhost:5000/getResult
I'm trying to call it via php with the following code.
$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();
I get this error:
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'data'
As for me you send only string @location\data_sample.csv
because command @
probably may work only in real curl
.
Based on PHP documentation you should use CURLFile or 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();
EDIT:
Full code which I used to test it.
main.py
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();
?>
Tested on Linux Mint 20
, PHP 7.4.3
, Python 3.8.5
.
I had to use /
instead of \
in 'location/data_sample.csv'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.