Python3+MySQL+Flask+Echarts

前提是MySQL上已经存在数据,我们使用python连接MySQL获取数据,接着用python的web框架Flask作为后台做,Echarts可视化。
简单演示:MySQL上的数据形如
在这里插入图片描述

  • 连接数据库-使用的库为import pymysql
  • HTML使用Echarts开源的模板-这里命名my_template.html
  • 使用的Flask库为:
  • from flask import Flask,render_template,url_for
app = Flask(__name__)
@app.route('/')
def my_tem():
    #在浏览器上渲染my_templaces.html模板
    return render_template('my_template.html')
@app.route('/test',methods=['POST'])
def my_test():
	#创建连接数据库
    connection = pymysql.connect(host='localhost',
                                 user='root',
                                 passwd='root',
                                 db='test',
                                 port=3306,
                                 charset='utf8'
                                 )
    cur=connection.cursor() #游标(指针)cursor的方式操作数据
    sql='SELECT movie,score FROM tbl_movie_score' #sql语句
    cur.execute(sql) #execute(query, args):执行单条sql语句。
    see=cur.fetchall() #使结果全部可看
    #print(sql)
   #print(see)
    #print(cur)
    #创建json数据
    xdays=[]
    jsonData={}
    yvalues=[]

    for data in see:
        xdays.append(data[0])
        yvalues.append(data[1])

    #print(xdays)
    #print(yvalues)

    jsonData['xdays']=xdays
    jsonData['yvalues']=yvalues

    #print(jsonData)
    #将json格式转成str,因为如果直接将dict类型的数据写入json会发生报错,因此将数据写入时需要用到该函数。
    j=json.dumps(jsonData,ensure_ascii=False)
    #print(j)
    cur.close()
    connection.close()
    #渲染html模板
    return (j)

if __name__ == "__main__":
    #运行项目
    #my_test() #测试
    app.run(debug = True) #整个项目的运行
  • HTML模板需要去官网上下载echarts.min.js,将其放在项目目录之下
  • my_template.html代码如下
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts</title>
    <!-- 引入 echarts.js -->
    <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
    <!-- 引入jquery.js -->
    <script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts.min.js"></script>
</head>
<body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

		//建立axjx所需的json数据	
        var app={
            xday:[],
            yvalue:[]
        };

        //发送ajax请求
        $(document).ready(function () {
       getData();
       console.log(app.xday);
       console.log(app.yvalue)
    });

	//设计画图
    function getData() {
         $.ajax({
         //渲染的是127.0.0.1/test 下的json数据
            url:'/test',
            data:{},
            type:'POST',
            async:false,
            dataType:'json',
            success:function(data) {
                app.xday = data.xdays;
                app.yvalue = data.yvalues;
                myChart.setOption({
                    title: {
                        text: '电影评分总数'
                    },
                    tooltip: {},
                    legend: {
                        data:['评分']
                    },
                    xAxis: {
                        data: app.xday
                    },
                    yAxis: {},
                    //
                    series: [{
                        name: '评分',
                        type: 'bar',
                        data: app.yvalue
                    }]
                })
            },
             error:function (msg) {
                console.log(msg);
                alert('系统发生错误');
            }
        })
    }
    </script>
</body>
</html>

  • 打开网页http://127.0.0.1:5000/就可以看到效果图了

在这里插入图片描述

  • 16
    点赞
  • 133
    收藏
    觉得还不错? 一键收藏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值