Web Server in Python

Wow! I thought Jetty was easy to set up, but a web server in Python takes the cake.

I need a server that responds with the same file no matter what GET request comes in – about the simplest server imaginable. And here it is:


from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

#Very simple web server that just gives the time of last request check
class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try :
            FILE = open(curdir + sep + "lastrun.txt") 
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(FILE.read())
            FILE.close()
            return
        except IOError:
            self.send_error(404, 'File Not Found')

try:
    server = HTTPServer(('', 9090), MyHandler)
    print 'started httpserver...'
    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down server'
    server.socket.close()

Twenty-four lines, and I didn’t even need to import anything outside the core language!

3 thoughts on “Web Server in Python”

  1. I can’t get python -m SimpleHTTPServer to work on my server. Should it work with the standard install packs?

Leave a Reply

Your email address will not be published. Required fields are marked *