16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 26 ■ PROJECT 7: YOUR OWN BULLETIN BOARD 495<br />

command, and because the database has been modified, conn.commit must be called so the<br />

changes aren’t lost when the script terminates.<br />

Listing 26-7 shows the source code for the save script.<br />

Listing 26-7. The Save Script (save.cgi)<br />

#!/usr/bin/python<br />

print 'Content-type: text/html\n'<br />

import cgitb; cgitb.enable()<br />

def quote(string):<br />

if string:<br />

return string.replace("'", "\\'")<br />

else:<br />

return string<br />

import psycopg<br />

conn = psycopg.connect('dbname=foo user=bar')<br />

curs = conn.cursor()<br />

import cgi, sys<br />

form = cgi.FieldS<strong>to</strong>rage()<br />

sender = quote(form.getvalue('sender'))<br />

subject = quote(form.getvalue('subject'))<br />

text = quote(form.getvalue('text'))<br />

reply_<strong>to</strong> = form.getvalue('reply_<strong>to</strong>')<br />

if not (sender and subject and text):<br />

print 'Please supply sender, subject, and text'<br />

sys.exit()<br />

if reply_<strong>to</strong> is not None:<br />

query = """<br />

INSERT INTO messages(reply_<strong>to</strong>, sender, subject, text)<br />

VALUES(%i, '%s', '%s', '%s')""" % (int(reply_<strong>to</strong>), sender, subject, text)<br />

else:<br />

query = """<br />

INSERT INTO messages(sender, subject, text)<br />

VALUES('%s', '%s', '%s')""" % (sender, subject, text)<br />

curs.execute(query)<br />

conn.commit()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!