Beginning Python Chapter 26

来源:互联网 发布:找房源的软件 编辑:程序博客网 时间:2024/05/29 09:05

Since I used the sqlite, so the codes are a little different from the books. Some points need to be noticed when do the coding.

1. For "print('<p><a href="view.cgi?id=%(id)i">%(subject)s</a></p>'% row)", you will transmit an "id" value to the link and you could receive the value by using the cgi.FieldStorage() method and getvalue() in the next cgi script.

2. You need to do the execute SQL sentence first to get the data and then run the fetch sentence to fetch the data.

3. If you want to get the value from the dictionary, you need to code as: '%(key)s'%dict.

Main.cgi

#!D:\Program Files\Python\python.exeprint('Content-type: text/html\n')import cgitb;cgitb.enable()import sqlite3conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')curs = conn.cursor()print("""<html>  <head>    <title>The FooBar Bulletin Board</title>  </head>  <body>    <h1>The FooBar Bulletin Board</h1>    """)curs.execute('SELECT * FROM messages')names = [d[0] for d in curs.description]rows = [dict(zip(names, row)) for row in curs.fetchall()]toplevel = []children = {}for row in rows:    parent_id = row['reply_to']    if parent_id is None:        toplevel.append(row)    else:        children.setdefault(parent_id,[]).append(row)def format(row):    print('<p><a href="view.cgi?id=%(id)i">%(subject)s</a></p>'% row)    try: kids = children[row['id']]    except KeyError: pass    else:        print('<blockquote>')        for kid in kids:            format(kid)        print('</blockquote>')print('<p>')for row in toplevel:    format(row)print("""</p><br /><p><a href="edit.cgi">Post message</a></p></body></html>""")

View.cgi

#!D:\Program Files\Python\python.exeprint('Content-type: text/html\n')import cgitb; cgitb.enable()import sqlite3conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')curs = conn.cursor()import cgi, sysform = cgi.FieldStorage()id = form.getvalue('id')print("""<html>  <head>    <title>View Message</title>  </head>  <body>    <h1>View Message</h1>    """)try: id = int(id)except:    print('Invalid message ID')    sys.exit()curs.execute('SELECT * FROM messages WHERE id = %i' %id)names = [d[0] for d in curs.description]rows = [dict(zip(names, row)) for row in curs.fetchall()]if not rows:    print('Unknown message ID')    sys.exit()row = rows[0]print("""<p><b>Subject:</b>%(subject)s<br /><b>Sender:</b>%(sender)s<br /><pre>%(text)s</pre></p><hr /><a href = 'main.cgi'>Back to the main page</a>| <a href = "edit.cgi?reply_to=%(id)s">Reply</a></body></html>""" %row)
Edit.cgi

#!D:\Program Files\Python\python.exeprint('Content-type: text/html\n')import cgitb; cgitb.enable()import sqlite3conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')curs = conn.cursor()import cgi, sysform = cgi.FieldStorage()reply_to = form.getvalue('reply_to')print("""<html>  <head>    <title>Compose Message</title>  </head>  <body>    <h1>Compose Message</h1>    <form action='save.cgi' method ='POST'>    """)subject =''if reply_to is not None:    print('<input type="hidden" name="reply_to" value="%s"/>'%reply_to)    curs.execute('SELECT subject FROM messages WHERE id = %s' %reply_to)    subject = curs.fetchone()[0]    if not subject.startswith('Re: '):        subject = 'Re: ' + subjectprint("""<b>Subject:</b><br /><input type='text' size='40' name='subject' value='%s' /><br /><b>Sender:</b><br /><input type='text' size='40' name='sender' /><br /><b>Message:</b><br /><textarea name='text' cols='40' rows='20'></textarea><br /><input type='submit' value='Save'/></form><hr /><a href='main.cgi'>Back to the main page</a></body></html>"""%subject)
Save.cgi

#!D:\Program Files\Python\python.exeprint('Content-type: text/html\n')import cgitb; cgitb.enable()def quote(string):    if string:        return string.replace("'","\\'")    else:        return stringimport sqlite3conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')curs = conn.cursor()import cgi, sysform = cgi.FieldStorage()sender = quote(form.getvalue('sender'))subject = quote(form.getvalue('subject'))text = quote(form.getvalue('text'))reply_to = quote(form.getvalue('reply_to'))if not (sender and subject and text):    print('Please supply sender, subject, and text')    sys.exit()if reply_to is not None:    query = """INSERT INTO messages(reply_to, sender, subject, text)VALUES(%s, '%s', '%s', '%s')"""%(int(reply_to), sender, subject, text)else:    query ="""INSERT INTO messages(sender, subject, text)VALUES('%s', '%s', '%s')"""%(sender, subject, text)curs.execute(query)conn.commit()print("""<html>  <head>    <title>Message Saved</title>  </head>  <body>    <h1>Message Saved</h1>    <hr />    <a href='main.cgi'>Back to the main page</a>  </body></html>""")




 
0 0