博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
flask+sqlite3+echarts2+ajax数据可视化--静态图
阅读量:7090 次
发布时间:2019-06-28

本文共 2234 字,大约阅读时间需要 7 分钟。

结构:

/www
|
|-- /static
| |
| |-- echarts.js(当然还有echarts原dist目录下的文件(夹))
|
|-- /templates
| |
| |-- index.html
|
|-- app.py
|
|-- create_db.py

一、先准备数据

# create_db.py# 只运行一次!!!import sqlite3# 连接conn = sqlite3.connect('mydb.db')c = conn.cursor()# 创建表c.execute('''DROP TABLE IF EXISTS weather''')c.execute('''CREATE TABLE weather (month text, evaporation text, precipitation text)''')# 数据# 格式:月份,蒸发量,降水量purchases = [('1月', 2, 2.6),             ('2月', 4.9, 5.9),             ('3月', 7, 9),             ('4月', 23.2, 26.4),             ('5月', 25.6, 28.7),             ('6月', 76.7, 70.7),             ('7月', 135.6, 175.6),             ('8月', 162.2, 182.2),             ('9月', 32.6, 48.7),             ('10月', 20, 18.8),             ('11月', 6.4, 6),             ('12月', 3.3, 2.3)            ]# 插入数据c.executemany('INSERT INTO weather VALUES (?,?,?)', purchases)# 提交!!!conn.commit()# 查询方式一for row in c.execute('SELECT * FROM weather'):    print(row)        # 查询方式二c.execute('SELECT * FROM weather')print(c.fetchall())# 查询方式二_2res = c.execute('SELECT * FROM weather')print(res.fetchall())# 关闭conn.close()

二、定义路由

定义了两个路由:'/'和'/weather',后一个用于处理ajax,返回json格式。形如:

{month:['1月','2月',...],evaporation:[3.1, 4, 4.6, ...],precipitation:[...]}

# app.pyimport sqlite3from flask import Flask, request, render_template, jsonifyapp = Flask(__name__)def get_db():    db = sqlite3.connect('mydb.db')    db.row_factory = sqlite3.Row    return dbdef query_db(query, args=(), one=False):    db = get_db()    cur = db.execute(query, args)    db.commit()    rv = cur.fetchall()    db.close()    return (rv[0] if rv else None) if one else rv@app.route("/", methods=["GET"])def index():    return render_template("index.html")@app.route("/weather", methods=["POST"])def weather():    if request.method == "POST":        res = query_db("SELECT * FROM weather")        return jsonify(month = [x[0] for x in res],                   evaporation = [x[1] for x in res],                    precipitation = [x[2] for x in res])if __name__ == "__main__":  app.run(debug=True)

三、使用echarts

这里使用单文件导入模式,。

值得注意的是导入echarts.js时使用了url_for函数。初时,我使用了src="js/echarts.js",老是导入不了!原因不详!

index.html文件如下:

    
ECharts Ajax

效果图

img_5028ed2cafea5d180bc76306e02bcf28.png

转载地址:http://nsbql.baihongyu.com/

你可能感兴趣的文章
沟通的艺术之幻灯片这奇女子
查看>>
一张图介绍CCIE
查看>>
VM增加centos6.5磁盘容量
查看>>
Servlet容器启动过程
查看>>
CentOS安装配置nagios(1)
查看>>
RedHat 6.4 搭建rhcs集群
查看>>
三生万物:决策树
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
Python爬虫框架Scrapy学习笔记原创
查看>>
大数据时代怎么做
查看>>
java基本语法
查看>>
细说HTTP之上篇
查看>>
将Eclipse Maven项目 导入 IDEA 步骤 成功运行 已测试!~LC
查看>>
Exchange Server 2010的俩种版本比较
查看>>
asp.net 插入视频
查看>>
laravel中的表单请求类型和CSRF防护(六)
查看>>
有1000瓶水,其中有一瓶有毒,小白鼠只要尝一点带毒的水24小时后就会死亡,至少要多...
查看>>
我的友情链接
查看>>
监控指定文件所有机器的网络状况
查看>>