Python CGI并发AJAX请求

2024-06-28 15:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我要做的是:我正在编写一个简单的轻量级IRC应用程序,托管在本地,基本上与Xchat相同,在你的浏览器中工作,就像Sabnzbd一样。我在浏览器中以html表的形式显示搜索结果,并使用ajaxget请求和on-unclick事件启动下载。我在1秒的循环中使用另一个ajaxget请求来请求下载信息(状态、进度、速度、ETA等)。由于我的CGI处理程序一次只能处理一个线程,所以我遇到了一个问题:实际上,主线程处理下载,同时请求下载状态。 因为我在某处有一个Django应用程序,所以我尝试实现这个IRC应用程序,一切都很好。同时请求被正确处理。 那么对于HTTP处理程序,我有什么需要知道的吗?基本CGI句柄不可能处理同时请求吗? 我在我的CGI IRC应用程序中使用以下内容:

from http.server import BaseHTTPRequestHandler, HTTPServer, CGIHTTPRequestHandler

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


Tags: 信息应用程序处理程序on状态htmlirc事件
2条回答

所以,经过进一步的研究,我的代码如下:

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

{a1}再深一点:

These four classes process requests synchronously; each request must be completed before the next request can be started.

DR:使用真正的web服务器。在

相关问题 更多 >