HTTPServer线程和进程

来源:互联网 发布:刘烨的演技 知乎 编辑:程序博客网 时间:2024/05/21 17:57

http://pymotwcn.readthedocs.org/en/latest/documents/BaseHTTPServer.html

 

线程和进程

HTTPServer是SocketServer.TCPServer的一个简单子类. 它不使用多线程或多进程来处理请求. 要增加多线程和多进程, 可以使用SocketServer中的合适的混用类来创建一个新的类.

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandlerfrom SocketServer import ThreadingMixInimport threadingclass Handler(BaseHTTPRequestHandler):    def do_GET(self):        self.send_response(200)        self.end_headers()        message = threading.currentThread().getName() ## 这里threading就可以自己处理        self.wfile.write(message)        self.wfile.write('\n')        returnclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):    """Handle requests in a separate thread."""if __name__ == '__main__':    server = ThreadedHTTPServer(('localhost', 8080), Handler)    print 'Starting server, use <Ctrl-C> to stop'    server.serve_forever()

每次当一个请求过来的时候, 一个新的线程或进程会被创建来处理它:

$ curl http://localhost:8080/Thread-1$ curl http://localhost:8080/Thread-2$ curl http://localhost:8080/Thread-3

如果把上面的ThreadingMixIn换成ForkingMixIn, 也可以获得类似的结果, 但是后者是使用了独立的进程而不是线程.

0 0