这依然是一个cgi的项目,有了前面的一个项目作为基础,这个里面没有什么难点。不过,和书上不同的是,我这里使用的数据库是mysql,所以有兴趣的童鞋,可以参考一下。
首先建立一张mysql的数据表:
CREATE TABLE messages( id INT NOT NULL AUTO_INCREMENT, subject VARCHAR(100) NOT NULL, reply_to INT, text MEDIUMTEXT NOT NULL, PRIMARY KEY(id) )
然后你要确定你的系统中已经安装了连接mysql的python模块,怎么确定呢。命令行下,进入python,然后输入import MySQLdb,注意大小写,如果没有报错,说明安装了,如果报错,从网上找python连mysql的方法,很多。
准备就绪,开始分析整个程序吧。
一个很简单的电子公告版,主要功能有,展示所有公告,查看单个公告,编辑公告,保存公告。所以根据功能建立四个文件:main.py,view.py,edit.py,save.py,每个文件,负责一个模块。
下面就上代码吧,太简单了。 main.py:
#!/usr/bin/python
print 'Content-type:text/html\n'
print
#import cgitb:cgitb.enable()
import MySQLdb
conn = MySQLdb.connect(db='usernet',host='127.0.0.1',user='root',passwd='root')
curs = conn.cursor()
print '''
<html>
<head>
<title>The UserNet</title>
</head>
<body>
<h1>The UserNet</h1>
'''
sql = 'SELECT * FROM message'
curs.execute(sql)
rows = curs.fetchall()
toplevel = []
children = {}
for row in rows:
parent_id = row[3]
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=%i">%s<a>' % (row[0],row[1])
try:
kids = children[row[0]]
except KeyError:
pass
else:
print '<blockquote>'
for kid in kids:
format(kid)
print '</blockquote>'
print '<p>'
for row in toplevel:
format(row)
print '''
</p>
<hr/>
<p><a href="edit.cgi">Post Message</a></p>
</body>
</html>
'''
view.py
#!/usr/bin/python
print 'Content-type:text/html\n'
import cgitb;cgitb.enable()
import MySQLdb
conn = MySQLdb.connect(db='usernet',host='127.0.0.1',user='root',passwd='root')
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 message WHERE id = %i' % id)
rows = curs.fetchall()
if not rows:
print 'Unknown message ID'
sys.exit()
row = rows[0]
print '''
<p><b>Subject:</b> %s<br/>
<b>Sender:</b>%s<br/>
<pre>%s</pre>
</p>
<hr/>
<a href='main.cgi'>Back to the main page</a>
|<a href="edit.cgi?reply_to=%s">Reply</a>
</body>
</html>
''' % (row[1],row[2],row[4],row[0])
edit.py
#!/usr/bin/python
print 'Content-type:text/html\n'
import cgitb;cgitb.enable()
import MySQLdb
conn = MySQLdb.connect(db='usernet',host='127.0.0.1',user='root',passwd='root')
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 message 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.py
#!/usr/bin/python
print 'Content-type:text/html\n'
import cgitb;cgitb.enable()
def quote(string):
if string:
return string.replace("'","\\'")
else:
return string
import MySQLdb
conn = MySQLdb.connect(db='usernet',host='127.0.0.1',user='root',passwd='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,text'
sys.exit()
if reply_to is not None:
query = """
INSERT INTO message(reply_to,sender,subject,text)
VALUES(%d,'%s','%s','%s')""" % (int(reply_to),sender,subject,text)
else:
query = """
INSERT INTO message(sender,subject,text)
VALUES('%s','%s','%s')""" % (sender,subject,text)
curs.execute(query)
conn.commit()
print '''
<html>
<head>
<title>Message Save</title>
</head>
<body>
<h1>Message Saved</h1>
<hr/>
<a href='main.cgi'>Back to the main page</a>
</body>
</html>s
'''