python练习六—简单的论坛
进行简单的web应用之后,接下来就应该学习python连接数据库,这个练习就是在上个练习的基础上将信息保存到数据库,这个联系也没有什么特别的,有之前java web的经验的话,很好理解,主要还是一个MySQLdb的学习。代码如下(创建数据库就忽略了吧):
从数据库查询message以列表的形式显示main.py
#! /usr/bin/env python
# -*- coding=utf-8 -*- import cgitb
import MySQLdb # 声明文本格式
print 'Content-type:text/html\n' cgitb.enable() # 连接数据库
conn = MySQLdb.connect(user='root', db='test')
curs = conn.cursor() print """
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>论坛帖子列表</h1>
""" # 将数据库中记录读取到dic
curs.execute('select * from messages')
# mysql没有这样的方法
# rows = curs.dictfetchall()
# 获取表的列的名称
names = [d[0] for d in curs.description]
print names
rows = [dict(zip(names, row)) for row in curs.fetchall()]
print rows # 主贴
toplevel = []
# 回复帖
children = {} # 区分出主贴和回复帖
for row in rows:
parent_id = row['reply_to']
if parent_id is None:
toplevel.append(row)
else:
children.setdefault(parent_id, []).append(row) # 格式化帖子列表
def format(row):
print '<p><a href="view.py?id=%(id)s">%(subject)s </a></p>'% row
try:
kids = children[row['id']]
except KeyError:
pass
else:
# 递归格式化帖子的子贴(回复)
print '<blockquote>'
for kid in kids:
format(kid)
print '</blockquote>'
print '<p>' # 调用format格式化帖子
for row in toplevel:
format(row) print """
</p>
<hr />
<p><a href="edit.py">发帖</a></p>
</bofy>
</html>
"""
查看一个具体帖子的详细内容view.py
#! /usr/bin/env python
# -*- coding=utf-8 -*- import cgitb
import sys
import cgi
import MySQLdb # 声明文本格式
print 'Content-type:text/html\n' cgitb.enable() # 接受参数
form = cgi.FieldStorage()
id = form.getvalue('id') try:
id = int(id)
except :
print 'Invalid id'
sys.exit() # 连接数据库
conn = MySQLdb.connect(user='root', db='test')
curs = conn.cursor() print """
<html>
<head>
<title>View message</title>
</head>
<body>
<h1>View Message</h1>
""" # 将数据库中记录读取到dic
curs.execute('select * from messages where id = %i' % id)
# mysql没有这样的方法
# rows = curs.dictfetchall()
# 获取表的列的名称
names = [d[0] for d in curs.description]
#print names
rows = [dict(zip(names, row)) for row in curs.fetchall()]
#print rows # 如果该id查询不到数据,说明不存在该id
if not rows:
print 'Unknow message id'
sys.exit() # 获取返回的第一条数据
row = rows[0] print """
<p>
<b> Subject: </b>%(subject)s <br />
<b> sender: </b>%(sender)s <br />
<pre>%(text)s</pre>
</p>
<hr />
<a href="main.py">back to main page</a>>
|
<a href="edit.py?reply_to=%(id)s"> reply</a>
</bofy>
</html>
""" % row
查看完帖子之后回帖,edit.py
#! /usr/bin/env python
# -*- coding=utf-8 -*- import cgitb
import sys
import cgi
import MySQLdb # 声明文本格式
print 'Content-type:text/html\n' cgitb.enable() # 接受参数
form = cgi.FieldStorage()
reply_to = form.getvalue('reply_to') # 连接数据库
conn = MySQLdb.connect(user='root', db='test')
curs = conn.cursor() print """
<html>
<head>
<title>View message</title>
</head>
<body>
<h1>View Message</h1>
<form action="save.py" method="POST">
""" subject = ''
if reply_to is not None:
print "<input type='hidden' name='reply_to' value='%s' />" % reply_to
curs.execute('select * from messages where id=%s' % reply_to)
subject = curs.fetchone()[1]
print subject
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.py'>Back to the main page</a>'
</body>
</html>
""" % subject
编辑完帖子的时候,提交save.py
#!/usr/bin/python
# -*- coding=utf-8 -*- print 'Content-type: text/html\n' import cgitb; cgitb.enable() # 将单引号转义,在使用insert语句的时候字符串就不需要添加引号
def quote(string):
if string:
return string.replace("'", "\\'")
else:
return string import MySQLdb
conn = MySQLdb.connect(db='test', user='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, and text'
sys.exit() if reply_to is not None:
query = """
insert into messages(reply_to, sender, subject, text)
values(%i, '%s', '%s', '%s')""" % (int(reply_to), sender, subject, text)
else:
query = """
insert into messages(sender, subject, text)
values('%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.py'>Back to the main page</a>
</body>
</html>s
"""
完整代码
http://pan.baidu.com/s/1gfbLDtx
python练习六—简单的论坛的更多相关文章
- 孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5
孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5并学习权限设置 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十二天. 今天继续学习mongo ...
- 孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4
孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十一天. 今天继续学习mongoDB的简单操作 ...
- 孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3
孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十天. 今天继续学习mongoDB的简单操作, ...
- 孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2
孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第九天. 今天继续学习mongoDB的简单操作, ...
- 孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1
孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第八天. 今天开始学习mongoDB的简单操作, ...
- 用Python写一个简单的Web框架
一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...
- 简学Python第六章__class面向对象编程与异常处理
Python第六章__class面向对象编程与异常处理 欢迎加入Linux_Python学习群 群号:478616847 目录: 面向对象的程序设计 类和对象 封装 继承与派生 多态与多态性 特性p ...
- 孤荷凌寒自学python第六十天在windows10上搭建本地Mongodb数据服务
孤荷凌寒自学python第六十天在windows10上找搭建本地Mongodb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第六天.成功在本地搭建了windows ...
- Python正则表达式的简单应用和示例演示
前一阵子小编给大家连续分享了十篇关于Python正则表达式基础的文章,感兴趣的小伙伴可以点击链接进去查看.今天小编给大家分享的是Python正则表达式的简单应用和示例演示,将前面学习的Python正则 ...
随机推荐
- Django forms表单 select下拉框的传值
今儿继续做项目,学习了Django的forms生成前端的代码. forms.py class SignupForm(forms.Form): username = forms.CharField(va ...
- Codeforces 1065 简要题解
文章目录 A题 B题 C题 D题 E题 F题 G题 传送门 GGG题略难,膜了一波zhouyuyang{\color{red} zhouyuyang}zhouyuyang巨佬的代码. 其余都挺清真的. ...
- 周报数据采集之生存图片(execl方法)
https://blog.csdn.net/Luzaofa/article/details/81675364 Python之Excel chart另存为图片大家好,好久没有更新博客了,这一段时间有点忙 ...
- Mybatis第二天
Mybatis第二天 框架课程 1. 课程计划 1.输入映射和输出映射 a) 输入参数映射 b) 返回值映射 2.动态sql a) If标签 b) Where标签 c) Sql片段 d) Fore ...
- 未能加载文件或程序集“ .....WebUI ”或它的某一个依赖项,试图加载格式不正确的程序
编译Web网站没有问题(需要引用oracle.dataAccess.dll),在运行时报错如下: 解决: 1. 将项目编译生成x86模式(win7 64位) 2. 有可能本机运行有问题,发布到IIS, ...
- html、css基础整理
1.块元素与行内元素之间的转换: HTML可以将元素分类方式分为行内元素.块状元素和行内块状元素三种.这三者是可以互相转换的,使用display属性能够将三者任意转换: (1)display:inli ...
- Java实现对文本文件MD5加密并ftp传送到远程主机目录
需求描述: 客户出完账之后需要把出账的数据以文本文件的方式传送给收入管理系统,客户以前是通过本地的一个工具软件上传的,由于安全监管的原因,不允许在本地使用工具上传,因此客户希望我们在已经上线使用的系统 ...
- codeforces 1066 B heater
菜鸡只配做水题 思路就很简单嘛:肯定扩展的越靠后边越好了 0 0 1 0 1 1 0 0 假设范围是3 ,第一个1一定要选上,第2.3个肯定选3啦,越靠后边就一定能节省更多的点,没看出来和子问题有什么 ...
- android项目生成aar和引用aar解决方案
引用依赖在项目中很常见,java开发一般是引用jar,所以android大家一般也是引用jar,但是android引用jar有时候会出现各种包冲突,很头痛!, 其实android有自己独特的引用aar ...
- Maven和Gradle的区别
转自:http://www.infoq.com/cn/news/2011/04/xxb-maven-6-gradle Maven面临的挑战 软件行业新旧交替的速度之快往往令人咂舌,不用多少时间,你就会 ...