我们使用pycharm编辑器,创建项目的时候记得直接创建flask项目,这样就会有现成的flask框架啦:
项目创建好就是这样的啦:
static是用于存放静态文件的,比如图片、css文件、js文件等;templates是用于存放html文件的;app.py就是用于存放路由器的了
要展示数据库的数据,主要思路就是连接数据库,获取需要的数据,再传给html页面接可以了。
所以首先要连接数据库:
conn = pymysql.connect( host='xxx.xxx.xxx.xxx', port='3306', user='xxxx', password='xxxxxx', database='test', charset='utf8', cursorclass=pymysql.cursors.DictCursor # 以字典的方式返回数据 ) cur = conn.cursor() # 获取游标
数据库表为:
然后要获取数据库的数据并返给html页面,所以app.py代码:
import pymysql from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): conn = pymysql.connect( host='xxx.xxx.xxx.xxx', port=3306, user='xxxx', password='xxxxxx', database='anne_test', charset='utf8', cursorclass=pymysql.cursors.DictCursor # 以字典的方式返回数据 ) cur = conn.cursor() # 获取游标 sql = 'select * from test' cur.execute(sql) # 执行sql data = cur.fetchall() # 查询所有行 cur.close() conn.close() return render_template('index.html',data = data) if __name__ == '__main__': app.run()
html文件index.html代码:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>web展示数据库数据</title> </head> <body> <table> <thead> <tr> <th>id</th> <th>username</th> <th>age</th> <th>sex</th> <th>native</th> </tr> </thead> <tbody> {% for i in data %} <tr> <td>{{ i['id'] }}</td> <td>{{ i['username'] }}</td> <td>{{ i['age'] }}</td> <td>{{ i['sex'] }}</td> <td>{{ i['native'] }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
html文件必须放在templates文件夹里,不然路由会找不到;
{% for i in data %}表示在data里进行循环,循环必须结束,所以有{% endfor %}
我们可以将data打印出来看一下他的数据结构:
可以看到data是一个列表,它的元素是字典,所以{% for i in data %}里的i就是字典,通过i['key']的方式获取字典指定key的value,这样就可以得到具体某个字段的值了
运行app.py,html文件的页面效果就是这样的了:
这样我们就实现了html展示数据库数据的功能了