|
@@ -0,0 +1,60 @@
|
|
1
|
+'''
|
|
2
|
+WSGI-compliant HTTP server. Dispatches requests to a pool of threads.
|
|
3
|
+https://github.com/RonRothman/mtwsgi
|
|
4
|
+'''
|
|
5
|
+
|
|
6
|
+from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
|
|
7
|
+import multiprocessing.pool
|
|
8
|
+
|
|
9
|
+__all__ = ['ThreadPoolWSGIServer', 'make_server']
|
|
10
|
+
|
|
11
|
+import bottle
|
|
12
|
+
|
|
13
|
+class ThreadPoolWSGIServer(WSGIServer):
|
|
14
|
+ '''WSGI-compliant HTTP server. Dispatches requests to a pool of threads.'''
|
|
15
|
+
|
|
16
|
+ def __init__(self, thread_count=None, *args, **kwargs):
|
|
17
|
+ '''If 'thread_count' == None, we'll use multiprocessing.cpu_count() threads.'''
|
|
18
|
+ WSGIServer.__init__(self, *args, **kwargs)
|
|
19
|
+ self.thread_count = thread_count
|
|
20
|
+ self.pool = multiprocessing.pool.ThreadPool(self.thread_count)
|
|
21
|
+
|
|
22
|
+ # Inspired by SocketServer.ThreadingMixIn.
|
|
23
|
+ def process_request_thread(self, request, client_address):
|
|
24
|
+ try:
|
|
25
|
+ self.finish_request(request, client_address)
|
|
26
|
+ self.shutdown_request(request)
|
|
27
|
+ except:
|
|
28
|
+ self.handle_error(request, client_address)
|
|
29
|
+ self.shutdown_request(request)
|
|
30
|
+
|
|
31
|
+ def process_request(self, request, client_address):
|
|
32
|
+ self.pool.apply_async(self.process_request_thread, args=(request, client_address))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+def make_server(host, port, app, thread_count=None, handler_class=WSGIRequestHandler):
|
|
36
|
+ '''Create a new WSGI server listening on `host` and `port` for `app`'''
|
|
37
|
+ httpd = ThreadPoolWSGIServer(thread_count, (host, port), handler_class)
|
|
38
|
+ httpd.set_app(app)
|
|
39
|
+ return httpd
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+class MTServer(bottle.ServerAdapter):
|
|
43
|
+ def run(self, handler):
|
|
44
|
+ thread_count = self.options.pop('thread_count', None)
|
|
45
|
+ server = make_server(self.host, self.port, handler, thread_count, **self.options)
|
|
46
|
+ try:
|
|
47
|
+ server.serve_forever()
|
|
48
|
+ except KeyboardInterrupt:
|
|
49
|
+ server.server_close() # Prevent ResourceWarning: unclosed socket
|
|
50
|
+ raise
|
|
51
|
+
|
|
52
|
+if __name__ == '__main__':
|
|
53
|
+ from wsgiref.simple_server import demo_app
|
|
54
|
+ httpd = make_server('', 8000, demo_app)
|
|
55
|
+ sa = httpd.socket.getsockname()
|
|
56
|
+ print "Serving HTTP on", sa[0], "port", sa[1], "..."
|
|
57
|
+ import webbrowser
|
|
58
|
+ webbrowser.open('http://localhost:8000/xyz?abc')
|
|
59
|
+ httpd.serve_forever()
|
|
60
|
+
|