Python中的multithreadingWeb服务器
我试图在python中创buildmultithreading的Web服务器,但它只响应一个请求,我不知道为什么。 你能帮我吗?
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from time import sleep class ThreadingServer(ThreadingMixIn, HTTPServer): pass class RequestHandler(SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') sleep(5) response = 'Slept for 5 seconds..' self.send_header('Content-length', len(response)) self.end_headers() self.wfile.write(response) ThreadingServer(('', 8000), RequestHandler).serve_forever()
从Doug Hellmann的博客上查看这篇文章。
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() 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()
下面是一个multithreading的SimpleHTTPServer-like HTTP服务器的另一个很好的例子: 在GitHub上的MultithreadedSimpleHTTPServer 。
这些突破stream式传输的解决scheme获得了多less票数呢? 如果可能需要stream式传输,那么ThreadingMixIn
和gunicorn就不好,因为它们只是收集响应,并将其作为一个单元写在最后(如果stream是无限的话,它实际上什么也不做)。
将BaseHTTPServer
与线程结合的基本方法是很好的。 但是,默认的BaseHTTPServer
设置会在每个侦听器上重新绑定一个新的套接字,如果所有侦听器都在同一个端口上,这在Linux中将不起作用。 在serve_forever()
调用之前更改这些设置。 (就像你必须在一个线程上设置self.daemon = True
来停止ctrl-C被禁用。)
以下示例在同一端口上启动100个处理程序线程,每个处理程序都通过BaseHTTPServer
启动。
import time, threading, socket, SocketServer, BaseHTTPServer class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path != '/': self.send_error(404, "Object not found") return self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # serve up an infinite stream i = 0 while True: self.wfile.write("%i " % i) time.sleep(0.1) i += 1 # Create ONE socket. addr = ('', 8000) sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(addr) sock.listen(5) # Launch 100 listener threads. class Thread(threading.Thread): def __init__(self, i): threading.Thread.__init__(self) self.i = i self.daemon = True self.start() def run(self): httpd = BaseHTTPServer.HTTPServer(addr, Handler, False) # Prevent the HTTP server from re-binding every handler. # https://stackoverflow.com/questions/46210672/ httpd.socket = sock httpd.server_bind = self.server_close = lambda self: None httpd.serve_forever() [Thread(i) for i in range(100)] time.sleep(9e9)
我开发了一个名为ComplexHTTPServer的PIP工具,它是SimpleHTTPServer的multithreading版本。
要安装它,所有你需要做的是:
pip install ComplexHTTPServer
使用它如下简单:
python -m ComplexHTTPServer [PORT]
(默认端口是8000.)