¿Cómo puedo ejecutar un script de Python a través de un servidor web y devolver los resultados a JavaScript?

I want to take results from a web page, sent from dom as json through ajax, then send this data to a python script, run it, then return the new results back as json. I was told a php script running gearman would be a good bet, but I'm still not sure how that would work.

preguntado el 09 de marzo de 12 a las 23:03

you can use PHP to call system scripts and programs, and it debemos capture anything echo'd back to it from those scripts. $return=system(/path/to/script.py); as long as the script is executable by your webserver. -

Make a python cgi and read the post/get parameters. -

Why would going through a PHP script even seem like a good idea? Just run the python script on the server. -

Agreed with @Wooble: the PHP script adds unnecessary complexity to the application. Have Python parse the JSON data, process it, and return the results as JSON. Then you simply need to get your web server to run Python. -

2 Respuestas

Here is my example using twisted y jquery.

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()

                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)

y el html

    <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" },
            }, "json");
<a href="javascript:void(0)" onclick="flipData()">Get Time</a>

respondido 10 mar '12, 00:03

Put your Python script in your CGI directory and use the cgi y json modules in your script to read AJAX from post/get params. Of course you puede do a system call from PHP to run a Python script, but I can't think of a good reason why you would.

respondido 10 mar '12, 00:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.