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

How can I run a python script through a webserver and return results to javascript?

本文关键字:结果 返回 javascript 脚本 Web 何通过 服务器 运行 python      更新时间:2023-09-26

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

下面是我使用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>

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