python:用flask快速实现数据可视化
Posted wedo创客实验室
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python:用flask快速实现数据可视化相关的知识,希望对你有一定的参考价值。
实验背景
最近『WedO实验君』需要弄一个实时刷新数据的监控面板,实验君今天和大家用python快速搭建一个实时动态的数据监控面板,请给实验君一首歌的时间。
● python
● flask
● pandas
● echarts
● jquery
● bootsrap
本实验没有采用jsp+java+tomcat,而是采用python的web轻框架flask。
flask基本应用
from flask import Flaskapp = Flask(__name__)
@app.route("/")
def hello():return "Hello World!"
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user return 'User %s' % username
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
if __name__ == '__main__': app.run()
路由app.route("/"): 即action ,设置url 的功能项目
含变量的路由@app.route('/user/<username>'):<variable_name>
模板render_template : {{ name }}
|
请求Request和响应Responses : 接收客户端的请求和响应数据给客户端
@app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) |
def Response_headers(content): resp = Response(content) resp.headers['Access-Control-Allow-Origin'] = '*' return resp @app.route('/response') def response_data(): dt = datetime.datetime.now() day=dt.strftime('%Y-%m-%d') d=pd.read_table("/home/yuyq/weixin/"+day+".list", sep=",", header=None,encoding='utf8') d.columns = [u"name"] data = list(d[u'name'].dropna()) #json.dumps(data) datas = {"data" : data} content = json.dumps(datas,cls=MyEncoder) print(content) resp = Response_headers(content) return resp |
flask 官方文档:http://flask.pocoo.org/ flask安装:
flask 部署:
|
# -*- coding: utf-8 -*- from flask import Flask, jsonify, render_template, request, Response import json import pandas as pd import numpy as np from datetime import datetime, date import datetime import time import pymysql app = Flask(__name__) class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(MyEncoder, self).default(obj) def Response_headers(content): resp = Response(content) resp.headers['Access-Control-Allow-Origin'] = '*' return resp @app.route("/") def index(): # 主页面 dt = datetime.datetime.now() day=dt.strftime('%Y-%m-%d') d=pd.read_table("/home/weixin/"+day+".list", sep=",", header=None,encoding='utf8') d.columns = [u"name"] subjects="" for index, row in d.iterrows(): if subjects == "": subjects= row['name'] else: subjects=subjects+"|"+ row['name'] ## 传递给参数给前端页面 return render_template("warn.html",lists=subjects) @app.route('/add1') def display(): dt = datetime.datetime.now() day=dt.strftime('%Y-%m-%d') d=pd.read_table("/home/xxx/weixin/"+day+"/all.dat", sep=",", header=None,encoding='utf8') d.columns = ["time","subject","cnt"] data = np.array(d.dropna()); json.dumps(data,cls=MyEncoder) datas = {"data" : data} content = json.dumps(datas,cls=MyEncoder) resp = Response_headers(content) return resp if __name__=="__main__": app.run(host = "192.168.29.16",port = 8880, debug = False) |
接收后台传递给模板的参数
{% ##获取模板的参数 set links=lists.split('|') %} {% for label in links %} {% set idLabel = label+"1" %} <div class="col-md-3 col-sm-3 col-xs-6"> <div class="x_panel"> <div class="x_content"> ##动态图标展示区域 <div id="{{label}}" style="height:200px;"></div> </div> </div> </div> {% endfor %} |
js 请求后台数据展示
//初始化表格控件 function setChartOption(){ for(var i=0;i<titles.length;i++){ console.log(); var tmp = echarts.init(document.getElementById(titles[i]), theme); tmp.setOption({ title: { text: titles[i], textStyle:{ fontSize:14 } }, tooltip: { trigger: 'axis' },
legend: { x: 230, y: 40 },
calculable: true, xAxis: [{ type: 'category', boundaryGap: false, data: [] }], yAxis: [{ type: 'value', min:0, max:100 }], series: [{ type: 'line', smooth: true, itemStyle: { normal: { areaStyle: { type: 'default' } } }, data: [] }] }); chart.set(titles[i], tmp); } } var $SCRIPT_ROOT = {{request.script_root|tojson|safe}}; function getData(){ var url = $SCRIPT_ROOT + '/add1'; var names=new Map(); var data = "type:1"; //请求后台数据flask $.ajax({ type : "get", async : false, //同步请求 url : url, data :{}, dataType :"json", timeout:5000, success:function(result){ if(result["data"].length > 3){ for(var i=4;i<result["data"].length;i++){ name=result["data"][i][1] if(names.has(name)){ l=names.get(name); l.push(result["data"][i]); names.set(name,l); }else{ l=[] l.push(result["data"][i]); names.set(name,l); } } } for (var [key, value] of chart) { var datas=[] var dates=[] for(var j=0; j<names.get(key).length;j++){ datas.push(names.get(key)[j][2]); dates.push(names.get(key)[j][0]); } value.setOption({ xAxis: [{ data:dates }], series: [{ data: datas }] }); } }, error: function() { } }); } // 每1分钟自动刷新数据 setInterval(getData,60000); getData(); |
部署:gunicorn -w 20 -b 192.168.29.16:8888 server:app
WedO实验君在本实验中用python+flask 搭建了简易的数据刷新平台。 flask简易而强大,通过route提供功能项,通过request和response 和前端进行交互。 前端通过ajax发送请求给后台。
◀◀◀ 长按二维码关注我
WedO实验君坚持原创内容,转载请留言。
以上是关于python:用flask快速实现数据可视化的主要内容,如果未能解决你的问题,请参考以下文章
25数据可视化:基于 Echarts + Python Flask框架动态实时大屏范例 - 企业宣传
数据可视化看板:基于 Echarts + Python Flask 动态实时大屏
数据可视化看板:基于 Echarts + Python Flask 动态实时大屏