Web Programming Languages

Python Source Code: dbread.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/
#----------------------------------------------------------

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

print textwrap.dedent("""\
  <div id="content">
    <h2>Python: Display MySQL Database Contents</h2>
    <table class='results db'>
      <tr><th>Park</th><th>City</th><th>State</th><th>Geo</th><th>Edit</th></tr>
""")

#----------------------------------------------------
#  The main Python code is here.
#  Everything else is boilerplate.
#----------------------------------------------------
if not mysql_available :
  print "<p id='error'>The MySQLdb module is not available on this server.</p>"
else :
  db = connect.my_connect()
  cursor = db.cursor()
  sql = "SELECT * FROM parks"
  # print sql # debug

  cursor.execute (sql)
  results = cursor.fetchall()

  # Draw an HTML table that has the database entry contents.
  for row in results :
    site  = row[0]
    state = row[1]
    city  = row[2]
    lat   = row[3]
    lon   = row[4]
    id    = row[5]
    print "<tr>"
    print "<td>" + site + "</td>"
    print "<td>" + city + "</td>"
    print "<td>" + state + "</td>"
  
    print "<td><a target='_blank' " + \
          "href='https://www.google.com/maps/preview/" + \
          "@%f,%f,12z'>%.2f, %.2f</a></td>" % \
          (lat, lon, lat, lon)
    print "<td><a href='dbedit.py?" + \
          "id=%d'><img src='../images/pencilc.svg' /></a>" % id
    print "</tr>"
#----------------------------------------------------

print textwrap.dedent("""\
    </table>
    <p><a href='dbwrite.py'>Write to this database table »</a></p>
    <p><a href='source.py?f=7'>Show Python source code »</a>
  </div>
""")

common.footers();