用Python超级简单仿163嵌套评论

用Python精纺163嵌套评论效果

先看图

下面开始简单学习

首先找个库(我就用mysql自带的test库)建立一张mysql的数据表:

DROP TABLE IF EXISTS `messages`;
CREATE TABLE `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subject` varchar(100) CHARACTER SET utf8 NOT NULL,
  `reply_to` int(11) unsigned NOT NULL DEFAULT '0',
  `text` mediumtext CHARACTER SET utf8 NOT NULL,
  `sender` varchar(50) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf-8;

然后你要确定你的系统中已经安装了连接mysql的python模块,怎么确定呢。命令行下,进入python,然后输入import MySQLdb,注意大小写,如果没有报错,说明安装了,如果报错,从网上找python连mysql的方法,很多。

准备就绪,开始分析整个程序吧。

一个很简单的电子公告版,主要功能有,展示所有公告,查看单个公告,编辑公告,保存公告。所以根据功能建立四个文件:main.py,view.py,edit.py,save.py,每个文件,负责一个模块。

下面就上代码吧。 main.py:

#!C:\Python\python.exe
#coding=utf-8

import MySQLdb
print "Content-type:text/html\r\n\r\n"
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
curs = conn .cursor()

str = ""
def get_tree(reply_to=0,steps=1):
    global str
    sql = "SELECT * FROM messages WHERE reply_to= %d" % reply_to
    curs.execute(sql)
    rows = curs.fetchall()
    if rows:
        for rs in rows:
            str += '<ul>'
            str += '<li>'
            str += '<div class="commentInfo"><span>主题:</span> <a href="view.py?id=%d">%s</a> <br/>' %(rs[0], rs[1])
            str += '<span>留言人:</span>{0}  <em class="floorCount">{1}层</em> <p class="content">{2}</p> <a href="edit.py?reply_to={3}">回复<font color="#ccc">{0}</font></a></div>' .format(rs[4], steps, rs[3], rs[0])
            get_tree(int(rs[0]),steps+1)
            str += '</li>'
            str += '</ul>'
    return str


print """
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>留言首页</title>
            <style>
               .commentInfo{color:#1e50a2;font-size:12px;padding-bottom:2px;}
                ul{position:relative;border:1px solid #999;background:none repeat scroll 0 0 #ffe;padding:3px;margin:1px 1px 15px;}
                ul li{list-style-type:none;}
                .floorCount{right:3px;top:0;position: absolute;color: #666;}
                .list{width:500px;margin:0px auto}
                .content{color:#2b2b2b;font-size:14px;}
            </style>
        </head>
        <body>
            <h1>留言列表</h1>
            <div class="list">"""
print get_tree()
print """   </div><hr/><p><a href="edit.py">新留言</a></p>
        </body>
    </html>
"""

view.py

#!C:\Python\python.exe
#coding=utf-8

import cgi
import MySQLdb
import sys
print "Content-type:text/html\r\n\r\n"
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
curs = conn .cursor()

#接收值
request = cgi.FieldStorage()
id = request.getvalue("id")
try:id = int(id)
except:
        print 'Invalid message ID'
        sys.exit()

#根据ID查询数据
sql = "SELECT * FROM messages WHERE id=%d" % id
curs.execute(sql)
rows = curs.fetchone()

print '''
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>留言详情</title>
  </head>
  <body>
    <h1>留言详情</h1>
    <p><b>主题:</b> %s<br/>
    <b>留言人:</b>%s<br/>
    <b>内容:</b><pre>%s</pre>
    </p><hr/>
    <a href='main.py'>返回首页</a>
       |
    <a href="edit.py?reply_to=%s">回复</a>
</body>
</html>
''' % (rows[1],rows[4],rows[3],rows[0])

edit.py

#!C:\Python\python.exe
#coding=utf-8

import cgi,MySQLdb,sys
print "Content-type:text/html\r\n\r\n"
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
curs = conn .cursor()

#接收值
request = cgi.FieldStorage()
reply_to = request.getvalue("reply_to")


print '''
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>留言</title>
    <style>
        form{width:500px;margin:0px auto}
        .col{width:300px;}
    </style>
  </head>
  <body>
    <h1>留言</h1>
    <form action='save.py' method='POST'>
'''
subject = ""
if reply_to is not None:
    try:
        reply_to = int(reply_to)
        #根据ID查询数据
        curs.execute("SELECT subject,sender FROM messages WHERE id=%d" % reply_to)
        msg=curs.fetchone()
        subject = msg[0]
    except:
            print 'Invalid message ID'
            sys.exit()
    print '<input type="hidden" name="reply_to" value="%s"/>' % reply_to
    start_with = "Re:  "
    if not subject.startswith(start_with):
        subject = start_with + subject

print '''
        <div class="col"><b>主题:</b><input type='text' size='40' name='subject' value='%s' /></div>
        <div class="col"><b>留言人:</b><input type='text' size='40' name='sender' /></div>
        <div class="col"><b>消息内容:</b><textarea name='text' cols='40' rows='20'></textarea></div>
        <div class="col"><input type='submit' value='留言  '/></div>
    </form>
    <hr/>
    <a href='main.py'>返回首页</a>
</body>
</html>
''' % subject

save.py

#!C:\Python\python.exe
#coding=utf-8

import MySQLdb
print "Content-type:text/html\r\n\r\n"
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
curs = conn .cursor()

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

#接收值
import cgi,sys
request = cgi.FieldStorage()


reply_to = addslashes(request.getvalue("reply_to"))
subject = addslashes(request.getvalue("subject"))
sender = addslashes(request.getvalue("sender"))
text = addslashes(request.getvalue("text"))


#判断
if (not sender) or (not subject) or (not text):
    print "Please "
    sys.exit()


#插入数据到库中去
if reply_to is not None:
    try:reply_to = int(reply_to)
    except:
            print 'Invalid message ID'
            sys.exit()
    sql = "INSERT INTO messages (reply_to,subject,sender,text) VALUES (%d,'%s','%s','%s')" % (reply_to, subject, sender, text)
else:
    sql = "INSERT INTO messages (subject,sender,text) VALUES ('%s','%s','%s')" % (subject, sender, text)
#print sql
#sys.exit()

curs.execute(sql)
conn.commit()

print '''
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>提交留言</title>
  </head>
  <body>
    <h1>留言已经提交</h1>
    <hr/>
    <a href='main.py'>回到首页</a>
  </body>
</html>
'''


赶快去试试吧

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值