Fosbenner.net

CGI Example 2

This script will generate a basic HTML document that will contain an unordered list of prime numbers within a certain range. For some context, see 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)

def is_prime(x):
   """check if number is prime"""
   from math import sqrt
   sq = sqrt(x)
   if sq.is_integer():
      # perfect square, not prime
      return False
   for i in xrange(2, int(sq)+1):
      if not (x % i):
         # found factor, not prime
         return False
   # made it this far, must be prime
   return True

## START EXECUTION ##
title = 'Prime Numbers'
desc = 'List of prime numbers in certain range'

# define range to check, inclusive
x = 10
y = 1000

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

out.append(st('body'))
out.append('\t' + elem('h1', 'List of primes between ' + str(x) + ' and ' + str(y)))
out.append('\t' + st('ul'))

# add a list item of every prime number
for i in xrange(x, y+1):
   if is_prime(i):
      out.append('\t\t' + elem('li', str(i)))

out.append('\t' + et('ul'))
out.append(et('body'))
out.append(et('html'))

for i in out:
   print i