A Simple Web Server in 30 Lines of Python Code

I haven’t recently had much time to do the fancy R&Ds I always loved! Today afternoon I was not feeling good to study, let alone that huge microeconomics assignment. I fired off the python interpreter and started coding aimlessly. I was inspecting the http.server module of Python 3 when an urge to create a web server popped into my mind. I started studying the Python 2.X docs and soon coded up a very simple web server. It can parse and serve dynamic pages (currently php, py and pyc files). It can not yet serve static files. :( And one more issue: If you run a phpinfo() with it, you won’t get a good looking output like you get on a LAMP, WAMP or MAMP.

To start the server, just use this command:

python server.py

Source Code:

 
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import os,glob
 
class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        fpath = os.path.join(os.getcwd(),self.path[1:])
        response = ""
        if os.path.isfile(fpath):
                response = open(fpath,"rb").read()
                if fpath[-3:] == 'php':
                    response = os.popen("php5 -f " + fpath).read()
                if fpath[-2:] == 'py':
                    response = os.popen("python " + fpath).read()
                if fpath[-3:] == 'pyc':
                    response = os.popen("python " + fpath).read()
        elif os.path.isdir(fpath):
                dirlist = glob.glob(fpath + "/*")
                response = "<html><head><title>Directory Listing of " + os.path.basename(fpath) + "</title><head>"
                response += "<body>"
                for x in dirlist:
                    response += "<a href=\"" + os.path.basename(x) + "\">" + os.path.basename(x) + "</a><br />"
                response += "</body></html>"
 
        self.send_response(200)
        self.send_header("Content-type","text/html")
        self.end_headers()
        self.wfile.write(str(response))
 
httpd = HTTPServer(('',7676),RequestHandler)
httpd.serve_forever()

I love you, Python! :D

This entry was posted in Blog Post and tagged . Bookmark the permalink.

2 Responses to A Simple Web Server in 30 Lines of Python Code

  1. Pingback: Tweets that mention A Simple Web Server in 30 Lines of Python Code « maSnun.com -- Topsy.com

  2. Pingback: A Simple Web Server in 30 Lines of Python Code « maSnun.com | Drakz Free Online Service

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">