Fosbenner.net

CGI Example 1

This script will generate a very basic HTML document. It is intended to be run as a CGI script. For some context, see the related article below.

Related article: Here

Click here to download script

#!/usr/bin/env python

## FUNCTION DEFINITIONS ##
def st(tag, attr=""):
   """Generate HTML start tag"""
   if attr != "": #pad attr with a space
      attr = " " + attr
   return '<' + tag + attr + '>'

def et(tag):
   """Generate HTML end tag"""
   return '</' + tag + '>'

def elem(tag, content, attr=""):
   """Generate whole element"""
   return st(tag, attr) + content + et(tag)

def eelem(tag, attr=""):
   """Generate empty element"""
   attr += ' /' # add space, slash to end
   return st(tag, attr)

## START EXECUTION ##
title = 'Example Site'
desc = 'This page is generated by Python!'

out = []
out.append('Content-Type: text/html\n')
out.append('<!DOCTYPE html>\n' + st('html') + '\n' +
   elem('head', '\n\t' +
   elem('title', title) + '\n\t' +
   eelem('meta', 'name="description" content="' + desc + '"') + '\n\t' +
   eelem('link', 'rel="stylesheet" href="https://fosbenner.net/s/playground.css"') + '\n'))

out.append(elem('body', '\n\t' +
   elem('h1', 'This is a header') + '\n\t' +
   elem('p', 'This is a paragraph') + '\n\t' +
   elem('p', 'This is another paragraph') + '\n'
   ) + '\n' + et('html'))

for i in out:
   print i