flask读取数据库(mysql)并展示表格(讲解获取表头的方法)【附上flask好看点的helloworld】

本文详细介绍如何使用Flask框架结合Bootstrap美化网页,并演示如何通过pymysql链接数据库,展示数据库内容于网页上,实现动态数据展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简述

为了网页的好看,最好还是用bootstrap

好看点的helloworld

anyway,先看初始版本的 helloworld

  • /template/index.html
  • 来自于bootstrap官网
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  </body>
</html>
  • ./app.py
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

在这里插入图片描述

链接数据库

这里我推荐使用pymysql
因为这个在不同平台上都可以使用,而且安装也没什么坑。

pip install pymysql
  • 链接的示范
    • conn是一个连接器
    • host是url
    • user是用户
    • password是密码
    • db是数据库(也就是show databases;可以看到的)
    • charset主要是为了设置为可以看中文
import pymysql


conn = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='1234',
    db='library_management_system',
    charset='utf8'
)

结合在html上和flask上

html代码修改

  • /templates/index.html
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-sm-12 col-xs-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3>Students</h3>
            </div>
            <div class="panel-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            {% for i in labels %}
                                <td>{{ i }}</td>
                            {% endfor %}
                        </tr>
                        </thead>
                        <tbody>
                        {% for i in content %}
                            <tr>
                                {% for j in i %}
                                    <td>{{ j }}</td>
                                {% endfor %}
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
</body>
</html>
  • app.py
from flask import Flask, render_template
import pymysql

app = Flask(__name__)

conn = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='1234',
    db='jxgl',
    charset='utf8'
)


@app.route('/')
def hello_world():
    cur = conn.cursor()

    # get annual sales rank
    sql = "select * from student"
    cur.execute(sql)
    content = cur.fetchall()

	# 获取表头
    sql = "SHOW FIELDS FROM student"
    cur.execute(sql)
    labels = cur.fetchall()
    labels = [l[0] for l in labels]

    return render_template('index.html', labels=labels, content=content)


if __name__ == '__main__':
    app.run()

  • 效果:

在这里插入图片描述

Flask是一个轻量级的Web应用框架,而MySQL是一个流行的关系型数据库管理系统。在Python中,你可以结合这两个工具构建一个web应用,从MySQL数据库获取数据,通过一些数据可视化库如Matplotlib、Plotly或Bokeh将数据展示出来。 以下是基本步骤: 1. **安装依赖**: - 安装 FlaskFlask-SQLAlchemy(用于数据库操作):`pip install flask flask-sqlalchemy` - 如果需要数据可视化,安装 matplotlib 或其他你喜欢的库:`pip install matplotlib` 2. **配置数据库连接**: 使用 `flask_sqlalchemy` 创建 SQLAlchemy 绑定到 MySQL 数据库: ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name' db = SQLAlchemy(app) ``` 记得替换上述代码中的 `username`、`password`、`localhost` 和 `db_name` 为你实际的数据库信息。 3. **创建模型**: 设计一个数据模型,比如 User 表: ```python class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True, nullable=False) # 添加其他你需要的字段 db.create_all() # 初始化表结构 ``` 4. **查询数据库**: 使用 SQLAlchemy 进行查询,例如获取所有用户: ```python users = User.query.all() ``` 5. **数据处理和可视化**: 获取到数据后,使用 matplotlib 将数据转换成图表: ```python import matplotlib.pyplot as plt # 对数据进行统计分析,然后绘制柱状图、折线图等 plt.bar([user.name for user in users], [user.age for user in users]) plt.xlabel('User') plt.ylabel('Age') plt.title('Users Age Distribution') plt.show() ``` 6. **视图函数**: 在 Flask 视图中,将数据查询和可视化结合起来: ```python @app.route('/data') def visualize_data(): data = User.query.all() # ... 执行数据处理和可视化 return render_template('your_chart.html', chart=chart) # 返回渲染后的HTML页面 ``` 别忘了在模板文件 `your_chart.html` 中显示生成的图表。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gc.collect()

公众号“肥宅Sean”欢迎关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值