I’m tryin to create a multithreaded HTTP server in Python 3.10 using ThreadingHTTPServer. However, ThreadingHTTPServer doesn’t seem to be working multithreadedly – each GET request waits for the previous one to finish. To simulate a long-running operation, I’m using time.sleep() and then making two simultaneous GET requests. Based on the timestamps, I can see that the second GET request waits for the first one to complete.
How can I fix this?
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
start = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
wait_time = random.randint(2, 6)
time.sleep(wait_time)
response = f"{start}: wait {wait_time}"
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(response.encode('utf-8'))
def start_http_server():
httpd = ThreadingHTTPServer( ("", 8080), Handler)
httpd.serve_forever()