Post by AnyKey on Jul 6, 2005 10:27:07 GMT -5
Okay, here's a simple CGI script that takes input from a form, parses the input, and appends it to the html file (a simple guestbook-like system).
#a simple cgi guestbook script
#by Eric Wood
import cgi, string
form = cgi.FieldStorage()
top = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<link rel=stylesheet href="http://www.anykey.nssfis.com/main.css" type="text/css">
<title>::anykey::</title>
</head>
<body>
<p id="logo"><img src="http://www.anykey.nssfis.com/logo.gif" alt="logo"></p>
<div id="links">
<ul>
<li><h4>Navigation</h4></li>
<li><a href="http://www.anykey.nssfis.com" id="current">home</a></li>
<li><a href="http://www.anykey.nssfis.com/python">python</a></li>
<li><a href="http://www.anykey.nssfis.com/resources">resources</a></li>
<li><a href="http://www.anykey.nssfis.com/web">web design</a></li>
<li><a href="http://www.anykey.nssfis.com/about">about me</a></li>
<li><a href="http://www.anykey.nssfis.com/rants">rants</a></li>
<li><a href="http://www.anykey.nssfis.com/links">links</a></li>
</ul>
</div>
<div id="content">
<h1>Comments</h1>
"""
bottom = """
<form method="post" action="form.py">
<p>Name:</p>
<p><input type="text" name="Name" size="20"></p>
<p><textarea name="Comment" rows="6" columns="40">Comments</textarea></p>
<p>
<input type="submit">
<input type="reset">
</p>
</form>
<div id="bottom">
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html401"
alt="Valid HTML 4.01!" height="31" width="88"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!">
</a>
</p>
</div>
</div>
</body>
</html>
"""
def notags(data):
[t]data = string.replace(data, ">", ">")
[t]data = string.replace(data, "<", "<")
[t]return data
def between(thing1, thing2, data):
[t]mark1 = string.find(data, thing1)
[t]if mark1 == -1:
[t][t]print "Could not find "+thing1+" in string."
[t]mark2 = string.find(data[mark1:len(data)], thing2)
[t]if mark2 == -1:
[t][t]print "Could not find "+thing2+" in string."
[t]return data[mark1+len(thing1):mark2+mark1]
if form.has_key("Name") and form.has_key("Comment"):
[t]name = form["Name"].value
[t]comment = form["Comment"].value
[t]name = notags(name)
[t]comment = notags(comment)
[t]file = open("comments.html", "r")
[t]main = between("<h1>Comments</h1>", "<form method=\"post\" action=\"form.py\">", file.read())
[t]file.close()
[t]file = open("comments.html", "w")
[t]new = "<p><b>Name:</b> "+name+"</p>\n<p><b>Comment:</b></p>\n<p>"+comment+"</p>\n<p><b>---------------------------------------</b></p>"
[t]main += new
[t]file.write(top + main + bottom)
[t]file.close()