進行簡單的web應用以後,接下來就應該學習python鏈接數據庫,這個練習就是在上個練習的基礎上將信息保存到數據庫,這個聯繫也沒有什麼特別的,有以前java web的經驗的話,很好理解,主要仍是一個MySQLdb的學習。代碼以下(建立數據庫就忽略了吧):html
從數據庫查詢message以列表的形式顯示main.pyjava
#! /usr/bin/env python # -*- coding=utf-8 -*- import cgitb import MySQLdb # 聲明文本格式 print 'Content-type:text/html\n' cgitb.enable() # 鏈接數據庫 conn = MySQLdb.connect(user='root', db='test') curs = conn.cursor() print """ <html> <head> <title>主頁</title> </head> <body> <h1>論壇帖子列表</h1> """ # 將數據庫中記錄讀取到dic curs.execute('select * from messages') # mysql沒有這樣的方法 # rows = curs.dictfetchall() # 獲取表的列的名稱 names = [d[0] for d in curs.description] print names rows = [dict(zip(names, row)) for row in curs.fetchall()] print rows # 主貼 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.py?id=%(id)s">%(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>' # 調用format格式化帖子 for row in toplevel: format(row) print """ </p> <hr /> <p><a href="edit.py">發帖</a></p> </bofy> </html> """
查看一個具體帖子的詳細內容view.pypython
#! /usr/bin/env python # -*- coding=utf-8 -*- import cgitb import sys import cgi import MySQLdb # 聲明文本格式 print 'Content-type:text/html\n' cgitb.enable() # 接受參數 form = cgi.FieldStorage() id = form.getvalue('id') try: id = int(id) except : print 'Invalid id' sys.exit() # 鏈接數據庫 conn = MySQLdb.connect(user='root', db='test') curs = conn.cursor() print """ <html> <head> <title>View message</title> </head> <body> <h1>View Message</h1> """ # 將數據庫中記錄讀取到dic curs.execute('select * from messages where id = %i' % id) # mysql沒有這樣的方法 # rows = curs.dictfetchall() # 獲取表的列的名稱 names = [d[0] for d in curs.description] #print names rows = [dict(zip(names, row)) for row in curs.fetchall()] #print rows # 若是該id查詢不到數據,說明不存在該id if not rows: print 'Unknow 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.py">back to main page</a>> | <a href="edit.py?reply_to=%(id)s"> reply</a> </bofy> </html> """ % row
查看完帖子以後回帖,edit.pymysql
#! /usr/bin/env python # -*- coding=utf-8 -*- import cgitb import sys import cgi import MySQLdb # 聲明文本格式 print 'Content-type:text/html\n' cgitb.enable() # 接受參數 form = cgi.FieldStorage() reply_to = form.getvalue('reply_to') # 鏈接數據庫 conn = MySQLdb.connect(user='root', db='test') curs = conn.cursor() print """ <html> <head> <title>View message</title> </head> <body> <h1>View Message</h1> <form action="save.py" method="POST"> """ subject = '' if reply_to is not None: print "<input type='hidden' name='reply_to' value='%s' />" % reply_to curs.execute('select * from messages where id=%s' % reply_to) subject = curs.fetchone()[1] print subject if not subject.startswith('Re:'): subject = 'Re:'+ subject print """ <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.py'>Back to the main page</a>' </body> </html> """ % subject
編輯完帖子的時候,提交save.pygit
#!/usr/bin/python # -*- coding=utf-8 -*- print 'Content-type: text/html\n' import cgitb; cgitb.enable() # 將單引號轉義,在使用insert語句的時候字符串就不須要添加引號 def quote(string): if string: return string.replace("'", "\\'") else: return string import MySQLdb conn = MySQLdb.connect(db='test', user='root') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() sender = quote(form.getvalue('sender')) subject = quote(form.getvalue('subject')) text = quote(form.getvalue('text')) reply_to = 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(%i, '%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.py'>Back to the main page</a> </body> </html>s """
完整代碼web