Search for '{{search_term}}'

Static web server in Python

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

When I've started to work on the Code And Talk site I did not know what I was building. I actually started out by collecting data about podcasts. I did not use a database but I wanted to have some kind of a display.

So instead of creating a dynamic site I opted for a static site that can be generated by a script and a few templates.

Such site can be served using Apache or Nginx, but on my development machine I don't have either of those. So I wrote a small web server serving the static files.


#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import os

class StaticServer(BaseHTTPRequestHandler):

    def do_GET(self):
        root = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'html')
        if self.path == '/':
            filename = root + '/index.html'
            filename = root + self.path

        if filename[-4:] == '.css':
            self.send_header('Content-type', 'text/css')
        elif filename[-5:] == '.json':
            self.send_header('Content-type', 'application/javascript')
        elif filename[-3:] == '.js':
            self.send_header('Content-type', 'application/javascript')
        elif filename[-4:] == '.ico':
            self.send_header('Content-type', 'image/x-icon')
            self.send_header('Content-type', 'text/html')
        with open(filename, 'rb') as fh:
            html =
            #html = bytes(html, 'utf8')

def run(server_class=HTTPServer, handler_class=StaticServer, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd on port {}'.format(port))


# vim: expandtab


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus