Beginning Python Chapter 26
2014-06-21 15:37
381 查看
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.exe
print('Content-type: text/html\n')
import cgitb;cgitb.enable()
import sqlite3
conn = 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.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
curs = conn.cursor()
import cgi, sys
form = 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.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
curs = conn.cursor()
import cgi, sys
form = 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: ' + 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.cgi'>Back to the main page</a>
</body>
</html>
"""%subject)
Save.cgi
#!D:\Program Files\Python\python.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
def quote(string):
if string:
return string.replace("'","\\'")
else:
return string
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
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 = 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>
""")
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.exe
print('Content-type: text/html\n')
import cgitb;cgitb.enable()
import sqlite3
conn = 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.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
curs = conn.cursor()
import cgi, sys
form = 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.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
curs = conn.cursor()
import cgi, sys
form = 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: ' + 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.cgi'>Back to the main page</a>
</body>
</html>
"""%subject)
Save.cgi
#!D:\Program Files\Python\python.exe
print('Content-type: text/html\n')
import cgitb; cgitb.enable()
def quote(string):
if string:
return string.replace("'","\\'")
else:
return string
import sqlite3
conn = sqlite3.connect(r'D:\Python Program\Chapter26\data.db')
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 = 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>
""")
相关文章推荐
- Beginning Python Chapter 26
- Beginning Python Chapter 25
- Beginning Python Chapter 27
- beginning python summary chapter 5 - 条件,循环和其他语句
- Beginning Python Chapter 21
- beginning python summary chapter 6 - 抽象
- beginning python summary chapter 2 - 列表和元组
- beginning python summary chapter 4 - 字典
- Beginning Python Chapter 28
- Beginning Python Chapter 3 Notes
- Beginning Python Chapter 1 Notes
- beginning python summary chapter 3 - 使用字符串
- Beginning Python Chapter 28
- Beginning Python Chapter 22
- 《Beginning Python From Novice to Professional》学习笔记五:Advanced String
- D:/Python26/lib/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import Immut
- FreeBSD python25 move to python26 as default version
- 《Beginning Python From Novice to Professional》学习笔记七:Statement
- python 26 连接 mysql 实例
- 《Beginning Python From Novice to Professional》学习笔记三:List