如何通过Web服务器运行python脚本并将结果返回给javascript?

时间:2012-03-09 23:18:15

标签: php javascript python gearman

我想从网页中获取结果,从dom作为json发送到ajax,然后将此数据发送到python脚本,运行它,然后将新结果作为json返回。我被告知一个运行gearman的php脚本会是一个不错的选择,但我仍然不确定它是如何工作的。

2 个答案:

答案 0 :(得分:1)

以下是使用twistedjquery的示例。

#!/usr/local/bin/python
import json
import time

from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource


class DataPage(Resource):
        isLeaf = True

        def render_GET(self, request):

                htmlFile = open("template.html")
                html = open("template.html").read()
                htmlFile.close()

                return html

        def render_POST(self, request):
                print request.args
                data = request.args['data'][0]
                print data
                return json.dumps(data[::-1])

resource = DataPage()
factory = Site(resource)
reactor.listenTCP(38123, factory)
reactor.run()

和html

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function flipData(){

            $.post("http://localhost:38123/", { data: "makeitbackwards" },
            function(data){
                    alert(data);
            }, "json");
        }
    </script>
</head>
<body>
<a href="javascript:void(0)" onclick="flipData()">Get Time</a>
</body>
</html>

答案 1 :(得分:0)

将您的Python脚本放在CGI目录中,并使用脚本中的cgijson模块从post / get参数中读取AJAX。当然你可以从PHP进行系统调用来运行Python脚本,但我想不出你为什么这么做的理由。