html-利用flask实现html展示数据库数据(每天都要学习噢)

我们使用pycharm编辑器,创建项目的时候记得直接创建flask项目,这样就会有现成的flask框架啦

我们使用pycharm编辑器,创建项目的时候记得直接创建flask项目,这样就会有现成的flask框架啦:

2172656-20210402091832614-434915319.png

项目创建好就是这样的啦:

2172656-20210402091933084-226488456.png

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()  # 获取游标


数据库表为:

2172656-20210402093351034-966964556.png

然后要获取数据库的数据并返给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打印出来看一下他的数据结构:

2172656-20210402100101836-1635274167.png

可以看到data是一个列表,它的元素是字典,所以{% for i in data %}里的i就是字典,通过i['key']的方式获取字典指定key的value,这样就可以得到具体某个字段的值了


运行app.py,html文件的页面效果就是这样的了:

2172656-20210402095245573-979052629.png

这样我们就实现了html展示数据库数据的功能了

  • 发表于 2021-04-06 12:31
  • 阅读 ( 1331 )
  • 分类:测试开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
anne
anne

7 篇文章

作家榜 »

  1. admin 10 文章
  2. anne 7 文章
  3. joelee 2 文章
  4. chenchen 1 文章
  5. CJ777 1 文章
  6. harry 1 文章
  7. AlLTyjrDKb 0 文章
  8. virmMUTzPANJXY 0 文章