A Simple Web Server in 30 Lines of Python Code
Saturday, January 16th, 2010I 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!
[...] This post was mentioned on Twitter by Abu Ashraf Masnun, Telletto. Telletto said: maSnun says… A Simple Web Server in 30 Lines of Python Code: I haven’t recently had much time to do the fancy R&… http://bit.ly/7ZAUc7 [...]
[...] here: A Simple Web Server in 30 Lines of Python Code « maSnun.com Share and [...]