我想为Python程序创建一个非常简单的基于HTML/AJAX的GUI.所以前端是一个HTML页面,它通过AJAX与程序通信.你能用python给我一个服务器端的最小实现SimpleHTTPServer.SimpleHTTPRequestHandler
吗?
一个简单的例子是文本字段和按钮.当按下按钮时,字段的内容被发送到服务器,然后服务器发回相应的答案.我知道在Python中有很多强大的解决方案,但我想保持这个非常简单.我已经为这样的服务器找到了一些很好的例子(例如这里),但到目前为止我还没有找到真正最小的服务器.
如果你想知道我为什么要以这种方式实现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代码中):
AJAX test
当然,将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()
使用WSGI参考实现.从长远来看,你会更快乐.
from wsgiref.simple_server import make_server, demo_app httpd = make_server('', 8000, demo_app) print "Serving HTTP on port 8000..." # Respond to requests until process is killed httpd.serve_forever()
demo_app相对容易编写; 它处理您的Ajax请求.