Friday, 18 July 2008

Minimalistic web server in Python

Sometimes it gets handy to have a very minimalistic web server, for sharing your favourite music with a friend or when testing webdesign layouts with various browsers on different machines.
It's very easy to write one in Python... Anyway, it's already written, you just launch it.
import sys
import BaseHTTPServer
import SimpleHTTPServer

listen = ":8080"
if len(sys.argv) > 1:
listen = sys.argv[1] + listen
listen = listen.split(":")[:2]
listen[1] = int(listen[1])
listen = tuple(listen)

httpd = BaseHTTPServer.HTTPServer(listen, SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
It serves the contents of the current directory. You can give it an argument like localhost:8080, 0.0.0.0 or :8000 to listen on different IP/port. But be warned that this simple stuff is very insecure!