【问题标题】:How can I run a python script through a webserver and return results to javascript?如何通过网络服务器运行 python 脚本并将结果返回到 javascript?
【发布时间】:2012-03-09 23:18:15
【问题描述】:

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

【问题讨论】:

  • 您可以使用 PHP 调用系统脚本和程序,它应该从这些脚本中捕获任何回显给它的内容。 $return=system(/path/to/script.py); 只要脚本可以由您的网络服务器执行。
  • 制作一个python cgi并读取post/get参数。
  • 为什么通过 PHP 脚本看起来是个好主意?只需在服务器上运行 python 脚本。
  • 同意@Wooble:PHP 脚本给应用程序增加了不必要的复杂性。让 Python 解析 JSON 数据,对其进行处理,并将结果作为 JSON 返回。然后你只需要让你的网络服务器运行 Python。

标签: php javascript python gearman


【解决方案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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2015-06-11
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多