Writing a Minimal Web Server in Python

Copying files from one host in your home network to another is easy using protocols like NFS or SMB. But if you just want to transfer a couple of files to a friend's computer in a foreign network, you have a lot of setup work to do (at least on Linux boxes). It would be much easier to just run a web server and let the other host download the files via HTTP in a web browser. Unfortunately, web servers aren't trivial to setup either.

Gladly, Python's standard library comes with lots of useful modules: Among them are BaseHTTPServer and SimpleHTTPServer which provide everything needed to implement a simple web server in pure python. The SimpleHTTPServer.SimpleHTTPRequestHandler class is a handler which serves the current working directory in a style similar to apache. Via your browser, you can click through directories and download individual files.

It was a matter of minutes to write the servehttp script. The script accepts parameters to set the server's port and for the directory to serve. Feel free to adjust it to your needs.

By the way: More advanced servers can be written using Twisted, an extremely flexible tool kit for networking applications.

social