我写了一个这样的python脚本:
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()
我想将此脚本用作 Web 服务并通过另一台机器的 php 脚本调用它。我调用 python web 服务的 php 脚本是这样的:
<?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);
... ?>
头文件'CallRest.inc.php'是:
<?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;
}
?>
该类GetPrint
工作正常,但我不知道如何将 post 参数传递给 python web 服务以及如何将它们访问到 class PostPrint
。