Python基礎教程__項目(公告板)

  由於最近學習Python,從最基礎的Python基礎教程學起,其中最後的十個項目還是很不錯的。個人認爲。本人新手,如有錯誤,還請指教。

書上用的是PostgreSQL,這裏用的是MySQL。由於這是一個CGI項目。所以事先需要準備一個可以運行CGI腳本的試驗環境。

本次用的是Apache運行cgi。配置網上很多。

其次需要創建一個數據表:

CREATE TABLE `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subject` varchar(100) NOT NULL,
  `sender` varchar(15) NOT NULL,
  `reply_to` int(11) DEFAULT NULL,
  `text` mediumtext NOT NULL,
  PRIMARY KEY (`id`)
)

一個簡單的公告板,主要功能:顯示所有公告、查看單個公告、編輯公告、保存公告、刪除公告(個人增加的)。根據這些功能可以創建五個對應的腳本:main.cgi、view.cgi、edit.cgi、save.cgi、delete.cgi

一、下面廢話省略,直接上代碼和運行圖片:

1、main.cgi

#!/usr/bin/python

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

import cgitb; cgitb.enable()
import MySQLdb

conn=MySQLdb.connect(host='localhost',user='root', db='blog')
curs=conn.cursor()

print """
<html>
  <head>
    <title>The Blog Bulletin</title>
  </head>
  <body>
    <h1>The Blog Bulletin</h1>
  """

curs.execute('select * from messages')
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> | <a href="delete.cgi?id=%i">Delete</a></p>' % (row[0],row[1],row[0])
    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>
"""

2、view.cgi

#!/usr/bin/python

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

import cgitb; cgitb.enable()
import MySQLdb

conn=MySQLdb.connect(host='localhost',user='root',db='blog')
curs=conn.cursor()

import cgi,sys
form=cgi.FieldStorage()
id=form.getvalue('id')

print """

<html>
  <head>
    <title>View Message</title>
  </head>
  <body>
    <h1>View Mesage</h1>
    """

try: id = int(id)
except:
    print 'Invalid message ID'
    sys.exit()

curs.execute('select * from messages 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 Home</a>
    | <a href='edit.cgi?reply_to=%s'>Reply</a>
  </body>
</html>
""" % (row[1],row[2],row[4],row[0])

3、edit.cgi

#!/usr/bin/python

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

import cgitb; cgitb.enable()
import MySQLdb

conn=MySQLdb.connect(host='localhost', user='root', db='blog')
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 Home</a>
  </body>
</html>
""" % subject

4、save.cgi

#!/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(host='localhost', user='root', db='blog')
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 'Plz supply sender, subject, and text'
    sys.exit()

if reply_to is not None:
    query = """
    insert into messages(reply_to, sender, subject, text)
    value(%i, '%s', '%s', '%s')""" % (int(reply_to), sender, subject, text)
else:
    query = """
    insert into messages(sender, subject, text)
    value('%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 Home</a>
  </body>
</html>s
"""

5、delete.cgi

#!/usr/bin/python

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

import cgitb; cgitb.enable()
import MySQLdb

conn=MySQLdb.connect(host='localhost', user='root', db='blog')
curs=conn.cursor()

import cgi, sys
form=cgi.FieldStorage()
id=form.getvalue('id')

print """

<html>
  <head>
    <title>Delete Page</title>
  </head>
  <body>
    <h1>Delete Page!</h1>
    """
try: id = int(id)
except:
    print "Invalid message ID."
    sys.exit()

print """
    <p>Delete subject object successful.<p>
""" 
curs.execute('delete from messages where id=%i' % id)
conn.commit()

print """
    </p>
    <hr />
    <p><a href="main.cgi">Back Home</a></p>
  </body>
</html>
"""


二、運行截圖

wKioL1SGu8WAqcUVAAD3dHLRbOw210.jpg

wKioL1SGu9fghd5PAADtRNGM4RI193.jpg

wKioL1SGu-OjxOm8AADKVDj7zvQ555.jpg

wKiom1SGu1ihjEjWAAC6zDmKTFw678.jpg

wKioL1SGvKvSmb2jAADNb2KBbsw350.jpg



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章