Fosbenner.net

CGI Example 3

This script will generate an HTML document with a list of prime numbers in a user-specified range. For 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 ##
import cgi

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

# define range to check, inclusive
x = int(cgi.FieldStorage().getvalue('x', '10'))
y = int(cgi.FieldStorage().getvalue('y', '1000'))

# in case x is set higher than y
if x > y:
   x,y = y,x

out = []
a = lambda s: out.append(s)
a('Content-Type: text/html\n')
a('<!DOCTYPE html>')
a(st('html'))
a(st('head'))
a('\t' + elem('title', title))
a('\t' + eelem('meta', 'name="description" content="' + desc + '"'))
a('\t' + eelem('link', 'rel="stylesheet" href="https://fosbenner.net/s/playground.css"'))
a(et('head'))
a(st('body'))
a('\t' + st('form'))
a('\t\t x: ' + eelem('input', 'type="number" name="x" value="' +
   str(x) + '"'))
a('\t\t y: ' + eelem('input', 'type="number" name="y" value="' +
   str(y) + '"'))
a('\t\t' + eelem('input', 'type="submit" value="Get Primes"'))
a('\t' + et("form"))
a('\t' + elem('h1', 'List of primes between ' +
   str(x) + ' and ' + str(y)))
a('\t' + st('ul'))

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

a('\t' + et('ul'))
a(et('body'))
a(et('html'))

for i in out:
   print i