#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 Demo CGI guestbook for python class.
 Jim Mahoney, Dec 17 2006
 copyright GPL 
"""

print "Content-type: text/html\n"
import cgitb; cgitb.enable()
import cgi, time

def get_file(filename):
    """Return the text from a given file."""
    the_file = open(filename, 'r')
    text = the_file.read()
    the_file.close()
    return text

def append_to_file(filename, text):
    """Append text to filename"""
    the_file = open(filename, 'a')
    the_file.write(text)
    the_file.close()

# get the submitted values
form = cgi.FieldStorage()
who = form.getvalue('who')
comment = form.getvalue('comment')

# if there's a comment, append it to comments file.
if comment:
    if not who:
        who = 'anonymous'
    when = time.asctime()
    comment_html = "On %s, %s said:\n<pre>%s</pre>\n<hr/>\n" \
                   % (when, who, comment)
    append_to_file('comments.html', comment_html)

# -- If I had a lot of variables, I'd use a loop like this :
# data = {}
# for variable in ('who', 'comment'):
#    data{variable} = form.getvalue(variable)

# read in the html file and comments
html = get_file('page.html')
comments = get_file('comments.html')

# put the comments into the html
comment_marker = '<!-- comments -->'
html = html.replace(comment_marker, comments)
print html
