I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please?
#!/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()
In python3, you can use the code below (https or http):
You will figure out this code will create a new thread to deal with every request.
Command below to generate self-sign certificate:
If you are using Flask, this blog is great.
Here is another good example of a multithreaded SimpleHTTPServer-like HTTP server: MultithreadedSimpleHTTPServer on GitHub.
Check this post from Doug Hellmann's blog.
I have developed a PIP Utility called ComplexHTTPServer that is a multi-threaded version of SimpleHTTPServer.
To install it, all you need to do is:
Using it is as simple as:
(By default, the port is 8000.)
It's amazing how many votes these solutions that break streaming are getting. If streaming might be needed down the road, then
ThreadingMixIn
and gunicorn are no good because they just collect up the response and write it as a unit at the end (which actually does nothing if your stream is infinite).Your basic approach of combining
BaseHTTPServer
with threads is fine. But the defaultBaseHTTPServer
settings re-bind a new socket on every listener, which won't work in Linux if all the listeners are on the same port. Change those settings before theserve_forever()
call. (Just like you have to setself.daemon = True
on a thread to stop ctrl-C from being disabled.)The following example launches 100 handler threads on the same port, with each handler started through
BaseHTTPServer
.