Reputation: 841
I write a python script like this:
import web
import commands
urls = ('getprint', 'GetPrint', 'postprint', 'PostPrint')
app = web.application(urls, globals())
class GetPrint:
def GET(self):
return "Hello, this is GetPrint function :D"
class PostPrint:
def POST(self):
# I don't know how to access to post data!!!
if __name__ == "__main__": app.run()
I want to use this script as a web service and call It via a php script from another machine. My php script to call the python web service is like this:
<?php ...
require('CallRest.inc.php');
...
$status = CallAPI('GET', "http://WEBSERVICE_MACHINE_IP:PORT/".$arg);
echo $status;
...
$data = array("textbox1" => $_POST["textbox1"]);
CallAPI('POST', 'http://WEBSERVICE_MACHINE_IP:PORT/'.$arg, $data);
... ?>
And the header file 'CallRest.inc.php' is:
<?php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
The class GetPrint
work correctly but I don't know how to pass the post parameters to the python web service and how to access them into class PostPrint
.
Upvotes: 1
Views: 1350
Reputation: 3202
To access POST data on your Python code you should define right after your def POST(self)
a variable such as data = web.input()
. Then you can access the fields as shown here, For example: data.param1
, data.name
, and so on. So your code should look as follows:
class PostPrint:
def POST(self):
data = web.input()
param1 = data.param1
name = data.name
...
Upvotes: 2