How to write a non blocking SimpleHTTPRequestHandler ?

Yassine Chaouche yacinechaouche at
Thu Apr 23 16:35:22 CEST 2015

Here is a simple multi-threaded python web application that uses only the stanard library modules : 

#!/usr/bin/env python
#-*- encoding=utf-8 -*-
import SimpleHTTPServer
import BaseHTTPServer
import SocketServer

class MyServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer):

class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_header('Content-Type', 'text/html')
        self.wfile.write("Hello world \n")

IP,PORT = "",8010

server = MyServer((IP,PORT),Handler)

It will send Hello world followed by a newline (so that when you invoke curl on the terminal it will nicely put the shell prompt a newline). You can simulate a non-responsive client with this little script : 

import socket
import requests

# This will leave an open a connection to our app.
conn = socket.create_connection(('localhost',8010))

# This will never get anything until conn.close() is called.
print requests.get('http://localhost:8010').text.strip()

If you don't inherit from the ThreadingMixIn, the application will get stuck when you launch the client script and any further requests (use curl or wget for example) will simply be postponed until is killed.

If you inherit from ThreadingMixIn, the application will nicely run the request handler on a new thread, making way for further requests to be handled.

More information about the Python-list mailing list