Multi threaded HTTP server in python for handling get requests

Viewed 920

I need to create a multithreaded web server in python 3, where each request gets a new thread. I followed a basic example from a blog. But, the server is always blocking, as sleep called in 1 thread blocks the other threads. Can someone help me on this?

Here is my code

import time
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
import threading


class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        print('start-->')
        time.sleep(5)
        print('end-->')
        self.wfile.write("Test".encode())


class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
    pass


def run():
    server = ThreadingSimpleServer(('0.0.0.0', 1234), Handler)
    server.serve_forever()


if __name__ == '__main__':
    run()

My problem is, If I send 2 requests to the server, the second one starts executing only after the first one is done. I need the sleep to be on a thread of it's own, without affecting the other threads. I will be grateful for any help.

0 Answers
Related