如何使用javascript客户端设置Python服务器端

Nik*_*nni 14 javascript python

因此,已经有一个Python程序设置在我必须构建的控制台上运行.我将使用Javascript为应用程序构建Web GUI界面.我怎么会:

一个.在不触及原始代码的情况下,处理这个Python程序的输入/输出.

湾 通过Javascript调用将控制台行输入发送到Python程序.我已经查看了原始HTTP请求/ AJAX,但我不确定我将如何将其作为输入发送到Python程序.

Log*_*gan 6

一个.处理程序的输入/输出:Pexpect.它使用起来相当简单,阅读随附的一些示例应该足以让你了解基础知识.

湾 Javascript界面​​:

好吧,我使用gevent,它是内置的WSGI服务器.(查看WSGI服务器(另一个)是什么).我应该注意,该程序将保持状态,因此您可以通过将会话ID返回到javascript客户端并将pexpect会话存储在全局变量或其他容器中来管理打开的会话,以便您可以完成程序的输入和输出跨多个独立的AJAX请求.然而,我把它留给你,因为那不是那么简单.

我的所有示例都是在点击您选择的内容后将POST请求放入其中.(它实际上不会起作用,因为没有设置某些变量.设置它们.)

以下是相关部分:

<!-- JavaScript -->
<script src="jquery.js"></script>
<script type="text/javascript">
function toPython(usrdata){
    $.ajax({
        url: "http://yoursite.com:8080",
        type: "POST",
        data: { information : "You have a very nice website, sir." , userdata : usrdata },
        dataType: "json",
        success: function(data) {
            <!-- do something here -->
            $('#somediv').html(data);
        }});
$("#someButton").bind('click', toPython(something));
</script>
Run Code Online (Sandbox Code Playgroud)

然后是服务器:

# Python and Gevent
from gevent.pywsgi import WSGIServer
from gevent import monkey
monkey.patch_all() # makes many blocking calls asynchronous

def application(environ, start_response):
    if environ["REQUEST_METHOD"]!="POST": # your JS uses post, so if it isn't post, it isn't you
        start_response("403 Forbidden", [("Content-Type", "text/html; charset=utf-8")])
        return "403 Forbidden"
    start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
    r = environ["wsgi.input"].read() # get the post data
    return r

address = "youraddresshere", 8080
server = WSGIServer(address, application)
server.backlog = 256
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

如果您的程序是面向对象的,那么集成它是相当容易的.编辑:不需要面向对象.我现在已经包含了一些Pexpect代码

global d
d = someClass()
def application(environ, start_response):
    # get the instruction
    password = somethingfromwsgi # read the tutorials on WSGI to get the post stuff
    # figure out WHAT to do
    global d
    success = d.doSomething()
    # or success = funccall()
    prog = pexpect.spawn('python someprogram.py')
    prog.expect("Password: ")
    prog.sendline(password)
    i = prog.expect(["OK","not OK", "error"])
    if i==0:
        start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
        return "Success"
    elif i==1:
        start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")])
        return "Failure"
    elif i==2:
        start_response("500 Internal Server Error", [("Content-Type", "text/html; charset=utf-8")])
        return "Error"
Run Code Online (Sandbox Code Playgroud)

我建议的另一个选择是Nginx + uWSGI.如果你愿意,我也可以给你一些例子.它为您提供了将Web服务器整合到设置中的好处.


jfs*_*jfs 5

要将数据从javascript透明地传递到外部Python程序,您可以使用WebSocket协议连接服务器和javascript,并使用stdin/stdout与服务器中的外部程序进行通信.

这是一个示例Python程序client.py:

#!/usr/bin/env python
"""Convert stdin to upper case."""
for line in iter(raw_input, 'quit'):
    print line.upper()
Run Code Online (Sandbox Code Playgroud)

我使用来自hello world websocket示例的代码创建了一个服务器,并且回答了如何在每个传入连接上创建新进程并将所有输入数据重定向到进程'stdin:

#!/usr/bin/python
"""WebSocket CLI interface."""
import sys
from twisted.application import strports # pip install twisted
from twisted.application import service
from twisted.internet    import protocol
from twisted.python      import log
from twisted.web.server  import Site
from twisted.web.static  import File

from txws import WebSocketFactory # pip install txws


class Protocol(protocol.Protocol):
    def connectionMade(self):
        from twisted.internet import reactor
        log.msg("launch a new process on each new connection")
        self.pp = ProcessProtocol()
        self.pp.factory = self
        reactor.spawnProcess(self.pp, sys.executable,
                             [sys.executable, '-u', 'client.py'])
    def dataReceived(self, data):
        log.msg("redirect received data to process' stdin: %r" % data)
        self.pp.transport.write(data)
    def connectionLost(self, reason):
        self.pp.transport.loseConnection()

    def _send(self, data):
        self.transport.write(data) # send back


class ProcessProtocol(protocol.ProcessProtocol):
    def connectionMade(self):
        log.msg("connectionMade")
    def outReceived(self, data):
        log.msg("send stdout back %r" % data)
        self._sendback(data)
    def errReceived(self, data):
        log.msg("send stderr back %r" % data)
        self._sendback(data)
    def processExited(self, reason):
        log.msg("processExited")
    def processEnded(self, reason):
        log.msg("processEnded")

    def _sendback(self, data):
        self.factory._send(data)


application = service.Application("ws-cli")

_echofactory = protocol.Factory()
_echofactory.protocol = Protocol
strports.service("tcp:8076:interface=127.0.0.1",
                 WebSocketFactory(_echofactory)).setServiceParent(application)

resource = File('.') # serve current directory INCLUDING *.py files
strports.service("tcp:8080:interface=127.0.0.1",
                 Site(resource)).setServiceParent(application)
Run Code Online (Sandbox Code Playgroud)

Web客户端部分,sendkeys.html:

<!doctype html>
<title>Send keys using websocket and echo the response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<script src="sendkeys.js"></script>
<input type=text id=entry value="type something">
<div id=output>Here you should see the typed text in UPPER case</div>
Run Code Online (Sandbox Code Playgroud)

并且sendkeys.js:

// send keys to websocket and echo the response
$(document).ready(function() {
    // create websocket
    if (! ("WebSocket" in window)) WebSocket = MozWebSocket; // firefox
    var socket = new WebSocket("ws://localhost:8076");

    // open the socket
    socket.onopen = function(event) {
    socket.send('connected\n');

    // show server response
    socket.onmessage = function(e) {
        $("#output").text(e.data);
    }

    // for each typed key send #entry's text to server
    $("#entry").keyup(function (e) {
        socket.send($("#entry").attr("value")+"\n");
    });
    }
});
Run Code Online (Sandbox Code Playgroud)

尝试一下: