Python CGI同步AJAX请求

时间:2015-09-22 08:50:02

标签: python ajax multithreading cgi simultaneous

所以这就是交易:我正在编写一个简单的轻量级IRC应用程序,在本地托管,基本上和Xchat一样工作,并且在浏览器中工作,就像Sabnzbd一样。我在浏览器中将搜索结果显示为html表,并使用带有on_click事件的AJAX GET请求启动下载。我在1秒循环中使用另一个AJAX GET请求来请求下载信息(状态,进度,速度,ETA等)。因为我的CGI处理程序似乎一次只能处理一个线程,所以我遇到了同时发生的AJAX请求:实际上,主线程处理下载,同时发送下载状态请求。 由于我在某个地方有一个Django应用程序,我尝试实现这个IRC应用程序,一切正常。正确处理同时请求。 那么我需要知道HTTP处理程序吗?使用基本CGI句柄处理同时请求是不是可能的? 我将以下内容用于我的CGI IRC应用程序:

from http.server import BaseHTTPRequestHandler, HTTPServer, CGIHTTPRequestHandler

如果它不是关于理论而是关于我的代码,如果它有帮助,我很乐意发布各种python脚本。

2 个答案:

答案 0 :(得分:0)

更深入the documentation

  

这四个类同步处理的请求;必须在下一个请求开始之前完成每个请求。

TL; DR:使用真实的网络服务器。

答案 1 :(得分:0)

因此,经过进一步的研究,这里是我的代码,其中有效:

from http.server import BaseHTTPRequestHandler, HTTPServer, CGIHTTPRequestHandler
from socketserver import ThreadingMixIn
import threading
import cgitb; cgitb.enable()  ## This line enables CGI error reporting
import webbrowser


class HTTPRequestHandler(CGIHTTPRequestHandler):
    """Handle requests in a separate thread."""
    def do_GET(self):
        if "shutdown" in self.path:
            self.send_head()
            print ("shutdown")
            server.stop()
        else:
            self.send_head()


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

    def shutdown(self):
        self.socket.close()
        HTTPServer.shutdown(self)

class SimpleHttpServer():
    def __init__(self, ip, port):
        self.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler)
        self.status = 1

    def start(self):
        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def waitForThread(self):
        self.server_thread.join()

    def stop(self):
        self.server.shutdown()
        self.waitForThread()

if __name__=='__main__':
    HTTPRequestHandler.cgi_directories = ["/", "/ircapp"]
    server = SimpleHttpServer('localhost', 8020)
    print ('HTTP Server Running...........')
    webbrowser.open_new_tab('http://localhost:8020/ircapp/search.py') 
    server.start()
    server.waitForThread()
相关问题