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.

Advertisements
This entry was posted in python and tagged , , , . Bookmark the permalink.

3 Responses to Writing a Minimal Web Server in Python

  1. paul says:

    Its even easier to use the test function built into SimpleHTTPServer by:-

    $python -m SimpleHTTPServer
    Serving HTTP on 0.0.0.0 port 8000 …

  2. mafr says:

    Yes, you’re right. The only drawback is that you can’t change the port number (or adjust other aspects).

    And of course it’s not half as much fun ;-)

    Cheers,
    Matthias

  3. ss2shaha says:

    $python -m SimpleHTTPServer 7777

    Will serve on port 7777.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s