您的位置:首页 > 编程语言 > Python开发

Python项目7:自定义公告板

2015-07-25 19:04 609 查看
代码地址:https://code.csdn.net/ranky2009/pythonsmallproject

Python版本:3.4.3

操作系统:win7

此项目是分析python基础教程(第二版)的项目7:自定义公告板。改为适合于win7和python3的版本。

运用cgi,在项目六中有介绍。

准备工作:

1. 安装Mysql

/article/10933045.html

2. 在python中连接Mysql

/article/10933047.html

3. 创建数据库以及表

create database MyBoard;

use MyBoard;

create table messages(

id INT NOT NULL AUTO_INCREMENT,

subject VARCHAR(100) NOT NULL,

sender VARCHAR(15) NOT NULL,

reply_to INT,

text MEDIUMTEXT NOT NULL,

PRIMARY KEY(id)

);

4. 添加数据到数据库

insert into messages values(1, 're: first email', 'li xiao', 2, 'good job, multi-text');

insert into messages values(null, 'first email', 'lucy', null, 'learn python for fun');

insert into messages values(null, 'test email', 'lily', null, 'just test email');

insert into messages values(null, 're: re: first email ', ' lucy ', 1, 'just test email');

项目代码:

1. main.cgi

#!D:\Program Files (x86)\Python3.4.3\python.exe

print('Content-type: text/html\n')

import cgi
import pymysql

conn=pymysql.connect(host='localhost', user='root', passwd='****', db='myboard', port=3306, charset='utf8')
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'] #获取reply_to的的值
if parent_id is None:#如果reply_to为空,那么就是toplevel
toplevel.append(row)
else:#如果reply_to不为空,则添加到子列表中
children.setdefault(parent_id, []).append(row)

def format(row):
print('<p><a href="view.cgi?id=%i">%s</a></p>' % (row['id'], row['subject']))#打印subject
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>
<hr />
<p><a href="edit.cgi">Post message</a></p>
</body>
</html>
""")


2. view.cgi

#!D:\Program Files (x86)\Python3.4.3\python.exe

print('Content-type: text/html\n')

import cgi
import pymysql
import sys

conn=pymysql.connect(host='localhost', user='root', passwd='****', db='myboard', port=3306, charset='utf8')
curs=conn.cursor()

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>%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['subject'], row['sender'], row['text'], row['id']))


3. edit.cgi

#!D:\Program Files (x86)\Python3.4.3\python.exe

print('Content-type: text/html\n')

import cgi
import pymysql
import sys

conn=pymysql.connect(host='localhost', user='root', passwd='****', db='myboard', port=3306, charset='utf8')
curs=conn.cursor()

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)


4. save.cgi

#!D:\Program Files (x86)\Python3.4.3\python.exe

print('Content-type: text/html\n')

import cgi
import pymysql
import sys

def quote(string):
if string:
return string.replace("'", "\\'")
else:
return string

conn=pymysql.connect(host='localhost', user='root', passwd='****', db='myboard', port=3306, charset='utf8')
curs=conn.cursor()

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 values(null, \'%s\', \'%s\', %i, \'%s\')
""" % (subject, sender, int(reply_to), text)
else:
sys.exit()

print(query)

curs.execute(query)
conn.commit()

print("""
<html>
<head>
<title>Message Saved</title>
</head>
<h1>Message Saved</h1>
<hr />
<a href='main.cgi'>Back to the main page</a>
</body>
</html>""")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: