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

How to set up Python server side with javascript client side

本文关键字:Python 服务器端 设置 客户端 何使用 javascript      更新时间:2024-04-30

因此,已经设置了一个在控制台上运行的Python程序,我必须在此基础上进行构建。我将使用Javascript为应用程序构建一个web GUI界面。如何:

a。在不接触原始代码的情况下处理这个Python程序的输入/输出。

b。通过Javascript调用向Python程序发送控制台行输入。我已经研究了原始HTTP请求/AAJAX,但我不确定如何将其作为输入发送到Python程序。

a。处理程序的输入/输出:Pexpect。它很容易使用,阅读随它一起分发的一些示例应该会教会你足够的知识来掌握基本知识。

b。Javascript接口:

嗯,我使用gevent,它是内置的WSGI服务器。(查找WSGI服务器(另一个)是什么)。我应该注意的是,这个程序将保持一个状态,因此您可以通过向javascript客户端返回会话ID并将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>

然后服务器:

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

如果你的程序是面向对象的,那么集成它会相当容易。编辑:不需要面向对象。我现在已经包含了一些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"

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

要将数据从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()

我使用helloworldwebsocket示例中的代码创建了一个服务器,SO回答了如何在每个传入连接上创建一个新进程,并将所有输入数据重定向到进程的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)

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>

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");
    });
    }
});

尝试一下:

  • 下载此要点
  • 安装twistedtxws:

    $ pip install twisted txws
    
  • 运行:

    $ twistd -ny wscli.py
    
  • 访问http://localhost:8080/

  • 点击sendkeys.html并键入一些

您可能想要Flask和json模块。

Django是另一种选择,但对于您的需求来说可能太高级了。

这取决于包装的应用程序类型以及GUI选项如何转换为应用程序命令。但你有两个目标:

  1. 编写一个包装器,允许您读取程序的输出并为其提供输入。

  2. 制作一个web服务器来接收GUI事件,并将其转换为命令以传递给您的"包装器"

我已经做了一些你需要做的事情。

  1. 从本质上讲,您需要将套接字流转换为谨慎的命令。这方面的实际工具是expect,以及它的任何包装器(我使用过pexpect,Python包装器,使用它有很好的体验)。

  2. 这部分可能并不简单。问题是,您的底层程序一直在运行,因此您的web服务器应该是状态完整的,以便跨请求了解程序。另一种选择是,您的web服务器只需重新连接到进程并发出它的命令,并在stdout流中遇到响应时发回响应,但最终响应时间可能会很长,这取决于程序的速度。此外,AJAX请求是异步的,而您的底层程序是同步的。所以,是的,这可能会变得相当复杂。这真的取决于你的程序。如果您可以添加一些关于程序和GUI的详细信息,这将有所帮助。