title: How to implement Post/Redirect/Get using Python with CGI
body: <p>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, </p>
  
  <blockquote>
    <p>To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#!/usr/bin/python
  
  
  print "Content-Type: text/html"
  
  #print "Location: http://34.212.128.254/hellopython.py"
  
  print """
      &lt;title&gt;NameSample&lt;/title&gt;
      &lt;form action="hellopython.py" method="post"&gt;
  
       First Name:&lt;br&gt;
       &lt;input type="text" name="firstname" autocomplete="off"&gt;&lt;br&gt;
       &lt;input type="submit" value="Submit" autocomplete="off"&gt;
      &lt;/form&gt;
  """
  
  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()
  </code></pre>
  
  <p>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.</p>