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_header('Content-type', 'text/plain')
        except IOError:
            self.send_error(404, 'File Not Found')

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

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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.