Python web server for documentation

In this blog post we can read about handy way to run a web server to serve files in current directory using Python. I wanted to use it in order to read a documentation for Haskell modules stored locally. Typing

python -m SimpleHTTPServer

was easy, but I wasn’t happy with the result. On main page there was index of all modules. That’s fine. However after choosing one I would see a directory with two entries:

  1. html (directory)
  2. LICENSE (file)

I wanted to skip right into ‘html’ directory. Here is code to do just that:

#!/usr/bin/python3

from http.server import *
import http.server
from os import system, chdir
import sys

def run(server_class=HTTPServer, handler_class=http.server.SimpleHTTPRequestHandler):
    server_address = ('', 4000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

class MyRequestHandler( http.server.SimpleHTTPRequestHandler ):
    def do_GET(self,*args,**kwds):
        tmp = self.path.split('/')
        # redirect?
        if (len(tmp) == 3) and (tmp[0] == tmp[2]) and tmp[0] == '':
            self.send_response(301)
            self.send_header('Location', self.path + 'html/')
        else:
            http.server.SimpleHTTPRequestHandler.do_GET(self,*args,**kwds)

if __name__ == '__main__':
    chdir('/home/tener/share/doc')
    run(handler_class=MyRequestHandler)

One remark: I decided write code compatible with new Python 3, since that was easy enough and likely to work with new versions for a long time.

Advertisements

~ by Tener on 25/09/2009.

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

 
%d bloggers like this: