python搭建http服務器

轉自:tycoon1988HTTPServer線程和進程

線程和進程

HTTPServer是SocketServer.TCPServer的一個簡單子類. 它不使用多線程或多進程來處理請求. 要增加多線程和多進程, 可以使用SocketServer中的合適的混用類來創建一個新的類.

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading

class 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')
        return

class 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, 也可以獲得類似的結果, 但是後者是使用了獨立的進程而不是線程.



發佈了53 篇原創文章 · 獲贊 20 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章