前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python项目练习七:自定义公告板

python项目练习七:自定义公告板

作者头像
the5fire
发布2019-02-28 15:43:18
4960
发布2019-02-28 15:43:18
举报

这依然是一个cgi的项目,有了前面的一个项目作为基础,这个里面没有什么难点。不过,和书上不同的是,我这里使用的数据库是mysql,所以有兴趣的童鞋,可以参考一下。

首先建立一张mysql的数据表:

::

代码语言:javascript
复制
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:

.. code:: python

代码语言:javascript
复制
#!/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

.. code:: python

代码语言:javascript
复制
#!/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

.. code:: python

代码语言:javascript
复制
#!/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

.. code:: python

代码语言:javascript
复制
#!/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
'''
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-01-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档