如何使用web.py模块将POST参数访问到python Web服务器?

时间:2015-09-12 13:58:40

标签: php python web.py post-parameter

我写了一个像这样的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);
... ?>

头文件&#39; CallRest.inc.php&#39;是:

<?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工作正常,但我不知道如何将帖子参数传递给python网络服务以及如何将其访问到班级PostPrint

1 个答案:

答案 0 :(得分:1)

要访问Python代码的POST数据,您应该在def POST(self)变量data = web.input()之后定义。然后,您可以访问here所示的字段,例如:data.param1data.name等。所以你的代码应如下所示:

class PostPrint:
  def POST(self):
     data = web.input()

     param1 = data.param1
     name = data.name
     ...