前面我们介绍了响应处理的两种方式,这边学习如何从数据库获取结果。简单来说,就是从数据库查询数据并显示在前端html页面上。因为涉及到数据库,所以,我们这里先要安装一个数据库软件,这里用mysql,具体看看下面步骤。
1.安装mysql数据库,并创建好数据库和表信息。
数据库Mysql如何安装,请看这篇文章。
表如何创建和填入值,请看这篇文章。
我们演示主要是输出前面两个字段,也就是红圈的位置,其他的字段,可以为空
2.安装mysql python client
因为我们需要用python代码去连接和操作mysql数据库,所以我们需要安装一个mysql python client,如何安装呢,这里你肯定是先安装了python环境,打开cmd窗口,直接输入命令:python -m pip install mysqlclient
3. 创建一个现实文章article的html模板
$def with (r)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>article</title>
</head>
<body>
<h1>articles list</h1>
<ul>
$for x in r:
<li>$x.get('aid') => $x.get('title')</li>
</ul>
</body>
</html>
主要上面第一行,$表示后面跟着是python代码,下面还有一个for循环遍历,用来显示数据库中标的值。把这个article.html放在桌面的templates文件夹下。
4. 修改hello.py内容
import web
import MySQLdb
import MySQLdb.cursors
render = web.template.render('templates')
urls = (
'/article', 'article',
'/index', 'index',
'/blog/\d+', 'blog',
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
return render.hello2()
class article:
def GET(self):
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306, cursorclass=MySQLdb.cursors.DictCursor)
cur = conn.cursor()
cur.execute('select * from articles')
r = cur.fetchall()
cur.close()
conn.close()
print (r)
return render.article(r)
class index:
def GET(self):
query = web.input()
return web.seeother("https://www.baidu.com")
class blog:
def POST(self):
data = web.input()
return data
def GET(self):
# get the request head
return web.ctx.env
if __name__ == "__main__":
app.run()
主要看article这个class下GET方法的定义,第一行是连接mysql数据库,需要hostname,用户名和密码,数据库名称,端口,最后表示获取数据格式,这里用字典。cmd用python去运行下hello.py,然后去浏览器打开127.0.0.1:8080/artile,效果如下图。
提示:这里有一个编码的问题,如果在article.html中<h1>中写成中文的,虽然我设置了编码格式是utf-8,但是web.py响应处理打开就是乱码,但是单独运行article.html文件就不会显示乱码,所以,我这个地方都换成了中文。