I've recently began making an Amazon Linux EC2 LAMP server using Python CGI. I'm making a simple script that stores a name submitted from a text box to a MySQL table and displays it from any other browser. I came across a problem where any browser I'm on asks to resend the data on refresh. For example, Firefox sends,
To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.
I went looking for ways to fix this and one of the ways I found was to use a Post/Redirect/Get design pattern. I haven't found any examples that use Python and CGI together, and I'm at a bit of a loss as to how this works - however, I think after implementing it I'll understand a bit better.
Here is the code:
#!/usr/bin/python
print "Content-Type: text/html"
#print "Location: http://34.212.128.254/hellopython.py"
print """
<title>NameSample</title>
<form action="hellopython.py" method="post">
First Name:<br>
<input type="text" name="firstname" autocomplete="off"><br>
<input type="submit" value="Submit" autocomplete="off">
</form>
"""
import cgi
form = cgi.FieldStorage()
pastName = form.getvalue("firstname")
import MySQLdb
db = MySQLdb.connect(host="DEFINITELY_NOT_LOCALHOST", # your host, usually localhost
user="INSERT_USER", # your username
passwd="INSERT_PASSWORD", # your password
db="users") # name of the data base
cur = db.cursor()
if form.getvalue("firstname") != None:
cur.execute("truncate user")
cur.execute("INSERT INTO user VALUE('"+pastName+"',1)")
db.commit();
cur.execute("SELECT * FROM user")
for row in cur.fetchall():
print row[0]
db.close()
else:
cur.execute("SELECT * FROM user")
for row in cur.fetchall():
print row[0]
db.close()
I understand that not all of this is important, but hey, I'm a novice and it's probably best I don't omit anything.