Python基础教程__项目(公告板)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS MySQL,高可用系列 2核4GB
简介:

  由于最近学习Python,从最基础的Python基础教程学起,其中最后的十个项目还是很不错的。个人认为。本人新手,如有错误,还请指教。

书上用的是PostgreSQL,这里用的是MySQL。由于这是一个CGI项目。所以事先需要准备一个可以运行CGI脚本的试验环境。

本次用的是Apache运行cgi。配置网上很多。

其次需要创建一个数据表:

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/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



本文转自Mr_陈 51CTO博客,原文链接:http://blog.51cto.com/chenpipi/1588007,如需转载请自行联系原作者

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
3月前
|
异构计算 Python
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
322 1
|
2月前
|
索引 Python
Python 列表切片赋值教程:掌握 “移花接木” 式列表修改技巧
本文通过生动的“嫁接”比喻,讲解Python列表切片赋值操作。切片可修改原列表内容,实现头部、尾部或中间元素替换,支持不等长赋值,灵活实现列表结构更新。
121 1
|
3月前
|
数据采集 存储 XML
Python爬虫技术:从基础到实战的完整教程
最后强调: 父母法律法规限制下进行网络抓取活动; 不得侵犯他人版权隐私利益; 同时也要注意个人安全防止泄露敏感信息.
682 19
|
3月前
|
API 语音技术 开发者
Python 项目打包,并上传到 PyPI,分享项目
本文介绍了如何使用 Poetry 打包并发布一个 Python 项目至 PyPI。内容包括:项目创建、配置 `pyproject.toml` 文件、构建软件包、上传至 PyPI、安装与使用。通过实例 iGTTS 展示了从开发到发布的完整流程,帮助开发者快速分享自己的 Python 工具。
|
3月前
|
人工智能 Shell Python
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
ERROR: pip’s dependency resolver does not currently take into 报错-Python项目依赖冲突的解决方案-优雅草优雅草卓伊凡
223 0
|
3月前
|
数据采集 存储 JSON
使用Python获取1688商品详情的教程
本教程介绍如何使用Python爬取1688商品详情信息,涵盖环境配置、代码编写、数据处理及合法合规注意事项,助你快速掌握商品数据抓取与保存技巧。
|
4月前
|
并行计算 算法 Java
Python3解释器深度解析与实战教程:从源码到性能优化的全路径探索
Python解释器不止CPython,还包括PyPy、MicroPython、GraalVM等,各具特色,适用于不同场景。本文深入解析Python解释器的工作原理、内存管理机制、GIL限制及其优化策略,并介绍性能调优工具链及未来发展方向,助力开发者提升Python应用性能。
261 0
|
4月前
|
数据采集 索引 Python
Python Slice函数使用教程 - 详解与示例 | Python切片操作指南
Python中的`slice()`函数用于创建切片对象,以便对序列(如列表、字符串、元组)进行高效切片操作。它支持指定起始索引、结束索引和步长,提升代码可读性和灵活性。

推荐镜像

更多