Web Programming Languages

Python Source Code: dbedit.py

#!/usr/bin/env python
import cgi
import textwrap
import os
import connect
import common

mysql_available = False
try: 
  import MySQLdb
  mysql_available = True
except ImportError:
  mysql_available = False

#----------------------------------------------------------
#   The Web Language Project
#   Mark Brautigam
#   May-June 2015
#   http://www.mixed-up.com/markb/
#----------------------------------------------------------

#----------------------------------------------------
def printForm (row, id) :
#----------------------------------------------------
  print textwrap.dedent("""\
      <form name='parksform' action='dbedit.py' method='POST'>
        <fieldset class='db'>
        <legend>Edit a park</legend>
        <table>
  """)
  print "<tr><td>Park:</td><td><input type='text' name='site' value='%s' /></td></tr>" % (row[0])
  print "<tr><td>City:</td><td><input type='text' name='city' value='%s' /></td></tr>" % (row[2])
  print "<tr><td>State:</td><td><input type='text' name='state' value='%s' /> <span>(4 characters max)</span></td></tr>" % (row[1])
  print "<tr><td>Latitude:</td><td><input type='text' name='lat' value='%s' /></td></tr>" % (row[3])
  print "<tr><td>Longitude:</td><td><input type='text' name='lon' value='%s' /></td></tr>" % (row[4])
  print "<input type='hidden' name='id' value='%d' />" % (id) #Python 2.6 only
  print textwrap.dedent("""\
          <tr><td></td><td><input type='submit' id='submit' name='submit' value='Edit' /></td></tr>
        </table>
        </fieldset>
      </form>
  """)

#----------------------------------------------------
def formHasData (formData) :
#----------------------------------------------------
   nData = len(formData)
   for i in range (0, nData) :
     if (formData[i].strip() != '') :
       return True;
   return False;

#----------------------------------------------------
def printFeedback (row) :
#----------------------------------------------------
  print "<p>The following data was edited in the data file: </p>";
  print "<table class='results'>";
  print "<tr><th>Field</th><th>Old data</th><th>New data</th></tr>"
  print "<tr><td>Park</td><td>%s</td><td>%s</td></tr>\n" % (row[0],site) 
  print "<tr><td>City</td><td>%s</td><td>%s</td></tr>\n" % (row[2],city) 
  print "<tr><td>State</td><td>%s</td><td>%s</td></tr>\n" % (row[1],state) 
  print "<tr><td>Latitude</td><td>%s</td><td>%s</td></tr>\n" % (row[3],lat) 
  print "<tr><td>Longitude</td><td>%s</td><td>%s</td></tr>\n" % (row[4],lon) 
  print  "</table>";

#----------------------------------------------------

# Get the ID hidden form field value, which is required
form   = cgi.FieldStorage()
id     = form.getvalue('id', '')
if (id == '') :
  print "Location: dbread.py\n\n";
id = int(id)

if mysql_available :
  # see if this database entry exists
  db = connect.my_connect()
  cursor = db.cursor()
  #sql = "SELECT * FROM parks WHERE id={}".format(id) #Python 2.6 only
  sql = "SELECT * FROM parks WHERE id=%d" % (id) 
  cursor.execute (sql)
  results = cursor.fetchall()
  if (len(results) < 1) :
    print "Location: dbread.py\n\n";

common.headers1();
print "p#error { border: 1px solid #c00; background-color: #ff8; padding: 0.5em 1em; }"
common.headers2();
print common.sidebarX("python", "dbedit", "py");

row = results[0]

# Get the other values from the form
site   = form.getvalue('site', '')
city   = form.getvalue('city', '')
state  = form.getvalue('state', '')
lat    = form.getvalue('lat', '')
lon    = form.getvalue('lon', '')
submit = form.getvalue('submit', '')

print textwrap.dedent("""\
  <div id="content">
    <h2>Python: Edit the MySQL database</h2>
""")

if not mysql_available :
  print "<p id='error'>The MySQLdb module is not available on this server.</p>"
else :
  printForm (results[0], id);

# We only do this section if they are submitting the form,
# but not when we are first drawing the form.
#
if (submit == "Edit" and formHasData([site, city, state, lat, lon])) :

  # special handling for integers
  if lat.strip() == '' :
    lat = 0;
  if lon.strip() == '' :
    lon = 0;
  if (not common.is_number(lat)) :
    lat = 0;
  if (not common.is_number(lon)) :
    lon = 0;
  if (len(state) > 4) :
    state = state[0:4];

  printFeedback (row);

  # database connection
  sql = "UPDATE parks SET site='%s', city='%s', state='%s', " % (site,city,state) + \
        "latitude=%s, longitude=%s WHERE ID=%d;" % (lat,lon,id);
  print sql # debug
  cursor.execute (sql)
  db.commit()
#----------------------------------------------------

print textwrap.dedent("""\
    <p><a href='dbread.py'>Show the contents of this database table »</a></p>
    <p><a href='source.py?f=9'>Show Python source code »</a>
  </div>
""")

common.footers();