我想为Python程序创建一个非常简单的基于HTML / AJAX的GUI。因此,前端是一个HTML页面,可通过AJAX与程序进行通信。您能否使用python给我提供服务器端的最小实现SimpleHTTPServer.SimpleHTTPRequestHandler?
SimpleHTTPServer.SimpleHTTPRequestHandler
一个简单的示例是文本字段和按钮。当按下按钮时,该字段的内容将发送到服务器,然后服务器将相应的答案发送回去。我知道Python中有许多强大的解决方案,但是我想保持它非常简单。我已经找到了这种服务器的一些很好的例子(例如here),但是到目前为止,我还无法提出一个真正最小的例子。
如果您想知道为什么我要以这种方式实现GUI:此应用程序的重点是在交互最少的情况下以美观的布局显示大量数据-因此使用HTML + CSS似乎最方便(而且我已经用于非交互式数据显示)。
好的,我想我现在可以回答我自己的问题。这是用于在服务器上计算数字平方的示例实现。如果有任何改进或误解,请告诉我。
python服务器文件:
import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE = 'frontend.html' PORT = 8080 class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """The test example handler.""" def do_POST(self): """Handle a post request by returning the square of the number.""" length = int(self.headers.getheader('content-length')) data_string = self.rfile.read(length) try: result = int(data_string) ** 2 except: result = 'error' self.wfile.write(result) def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" server_address = ("", PORT) server = BaseHTTPServer.HTTPServer(server_address, TestHandler) server.serve_forever() if __name__ == "__main__": open_browser() start_server()
…和HTML文件(我称之为“ frontend.html”,不幸的是,该名称也必须出现在JavaScript代码中):
<html> <head> <title>AJAX test</title> </head> <body> <script type="text/javascript"> function xml_http_post(url, data, callback) { var req = false; try { // Firefox, Opera 8.0+, Safari req = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } req.open("POST", url, true); req.onreadystatechange = function() { if (req.readyState == 4) { callback(req); } } req.send(data); } function test_button() { var data = document.test_form.test_text.value; xml_http_post("frontend.html", data, test_handle) } function test_handle(req) { var elem = document.getElementById('test_result') elem.innerHTML = req.responseText } </script> <form name=test_form> sqr( <input type="text" name="test_text" value="0" size="4"> ) = <span id="test_result">0</span> <input type=button onClick="test_button();" value="start" title="start"> </form> </body> </html>
当然,将jQuery用于XML请求会更加方便,但是为了简单起见,我将其保留为原来的样子。
最后,使用WSGI的另一种实现(不幸的是,如果请求不是POST的话,我看不到依靠标准文件服务处理程序的方法):
import threading import webbrowser from wsgiref.simple_server import make_server FILE = 'frontend.html' PORT = 8080 def test_app(environ, start_response): if environ['REQUEST_METHOD'] == 'POST': try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(int(request_body) ** 2) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open(FILE).read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" httpd = make_server("", PORT, test_app) httpd.serve_forever() if __name__ == "__main__": open_browser() start_server()