[Tutor] Re: Please advice me on my code

Lee Harr missive at hotmail.com
Tue Sep 28 23:29:59 CEST 2004


import sys, os
import cgi
import cgitb; cgitb.enable()

import pg


def form():
    print """<form method="post" action="">

<p><input type=radio name="qtype"value="shot_number" checked />Shot 
Number<br />
<input type=radio name="qtype" value="project" />Project
</p>

<p>Type your keywords search here:<br>
<textarea name="qtext" value="" rows=2 cols=80 type="text"></textarea>
</p>

<input type="submit" value="SEARCH"><br>
</form>"""



print "Content-Type: text/html\n\n"
print '<head><title>The Title</title></head><body>'


if __name__ == "__main__":

    data = cgi.FieldStorage()

    if data:
        qtype = data['qtype'].value
        try:
            qtext = data['qtext'].value
        except KeyError:
            qtext = ''

        if qtext and qtype=="shot_number":
            print "You typed this:", qtext

            # Now, we can get to the database...
            db = pg.connect('test', user='test', passwd='testpasswd')

            # This next line is not the right way to do this. You want
            # to use the db connector's quoting system, but I do not see
            # how to do that with the pg module. This method will leave
            # you wide open to SQL injection attacks... be forewarned!
            #
            # I recommend asking on comp.lang.python if you cannot find
            # more assistance here on tutor.
            query = "select * from a where x=%(qtext)s" % {'qtext': qtext}
            # a is a table with 2 columns (x int, y text)

            qresult = db.query(query)

            listOfResults = qresult.dictresult()

            print "<p>Example of pulling the list of dictionary results 
apart.</p>"

            for record in listOfResults:
                print "<p><table>"
                for k in record.keys():
                    print '<tr>'
                    print '<td>key:</td> <td>', k, '</td>'
                    print '<td>value:</td><td>', record[k], '</td>'
                    print '</tr>'
                print '</table></p>'

            db.close()


        elif qtext and qtype == "project":
            print "You typed this:", qtext


        elif not qtext:
            print 'no text entered'

    else:
        form()

print '<body></html>'

_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail



More information about the Tutor mailing list