A program from the previous lecture
#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
import pymysql as db
print('Content-Type: text/html')
print()
form_data = FieldStorage()
bandname = ''
result = ''
if len(form_data) != 0:
try:
bandname = escape(form_data.getfirst('bandname'))
connection = db.connect('localhost', 'userid', 'password', 'database_name')
cursor = connection.cursor(db.cursors.DictCursor)
cursor.execute("""SELECT gig_date FROM gigs
WHERE band = '%s'""" % (bandname))
result = """<table>
<tr><th>Gig Dates</th></tr>"""
for row in cursor.fetchall():
result += '<tr><td>%s</td></tr>' % row['gig_date']
result += '</table>'
cursor.close()
connection.close()
except db.Error:
result = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'
print("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" >
<title>Gigs by band</title>
</head>
<body>
<form action="band_gigs.py" method="get">
<label for="bandname">Band: </label>
<input type="text" name="bandname" value="%s" size="50" maxlength="50" id="bandname" />
<input type="submit" value="Search for gigs" />
</form>
%s
</body>
</html>""" % (bandname, result))
Another database program
#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
import pymysql as db
print('Content-Type: text/html')
print()
form_data = FieldStorage()
bandname = ''
when = ''
result = ''
if len(form_data) != 0:
try:
bandname = escape(form_data.getfirst('bandname'))
when = escape(form_data.getfirst('when'))
connection = db.connect('localhost', 'userid', 'password', 'database_name')
cursor = connection.cursor(db.cursors.DictCursor)
cursor.execute("""INSERT INTO gigs (band, gig_date)
VALUES (%s, %s)""", (bandname, when))
connection.commit()
result = '<p>Succesfully inserted!</p>'
cursor.close()
connection.close()
except db.Error:
result = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'
print("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Insert gigs</title>
</head>
<body>
<form action="new_gigs.py" method="post">
<label for="bandname">Band: </label>
<input type="text" name="bandname" value="%s" size="50" maxlength="50" id="bandname" />
<label for="when">Date: </label>
<input type="date" name="when" value="%s" id="when" />
<input type="submit" value="Insert" />
</form>
%s
</body>
</html>""" % (bandname, when, result))