Highstock+flask+mysql实现多线条动态刷新

server端:

flask web服务器,接受请求返回数据

from flask import Flask,render_template,request
from mysql import MySql
import time
import datetime
import random
import json

app = Flask(__name__)


def get_data_buyer(sql):
    mysql = MySql()
    datas = mysql.query_data(sql)
    return parse_data_from_db(datas, 'ts', 'buyer')


def get_data_seller(sql):
    mysql = MySql()
    datas = mysql.query_data(sql)
    return parse_data_from_db(datas, 'ts', 'seller')


def get_data_user(sql):
    mysql = MySql()
    datas = mysql.query_data(sql)
    return parse_data_from_db(datas, 'ts', 'login_user')


def _datetime2timestamp(dt):
    date_format = "%Y-%m-%d %H:%M:%S"
    return time.mktime(time.strptime(str(dt), date_format))


def _timestamp2datetime(ts):
    date_format = "%Y-%m-%d %H:%M:%S"
    return time.strftime(date_format, time.localtime(ts))


def parse_data_from_db(data, field_ts=None, field_other=None):
    if len(data) == 0:
        return [], None

    results = []
    max_time = 0.0
    for item in data:
        temp = []
        ts = _datetime2timestamp(item.get(field_ts))
        temp.append(ts * 1000)
        if field_other == 'login_user':
            temp.append(int(item.get(field_other)) / 100)
        else:
            temp.append(int(item.get(field_other)))
        if ts > max_time:
            max_time = ts
        results.append(temp)
    return results, _timestamp2datetime(max_time)


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


@app.route('/data')
def data():

    if int(request.args.get('max_time_buyer', 0)) == 0:
        sql_buyer = "select * from t_buyer"
    else:
        last_time_buyer = _timestamp2datetime(float(request.args.get('max_time_buyer', 0)) / 1000.0)
        sql_buyer = "select * from t_buyer where unix_timestamp(ts) > unix_timestamp(" + '"' + last_time_buyer + '"' + ")"

    if int(request.args.get('max_time_seller', 0)) == 0:
        sql_seller = "select * from t_seller"
    else:
        last_time_seller = _timestamp2datetime(float(request.args.get('max_time_seller', 0)) / 1000.0)
        sql_seller = "select * from t_seller where unix_timestamp(ts) > unix_timestamp(" + '"' + last_time_seller + '"' + ")"

    if int(request.args.get('max_time_user', 0)) == 0:
        sql_user = "select * from t_user"
    else:
        last_time_user = _timestamp2datetime(float(request.args.get('max_time_user', 0)) / 1000.0)
        sql_user = "select * from t_user where unix_timestamp(ts) > unix_timestamp(" + '"' + last_time_user + '"' + ")"

    arr = {}
    data_buyer, max_time_buyer_str = get_data_buyer(sql_buyer)
    data_seller, max_time_seller_str = get_data_seller(sql_seller)
    data_user, max_time_user_str = get_data_user(sql_user)

    arr['data_buyer'] = data_buyer
    arr['data_seller'] = data_seller
    arr['data_user'] = data_user

    return json.dumps(arr)


def start_server():
    app.run(host='0.0.0.0',port=9999,debug=True)


if __name__=='__main__':
    start_server()

js文件:

周期性向server请求数据,计算最晚的时间,请求新数据并显示

function find_max_time(times){
    max_time = times[0][0]
    for(i=1; i < times.length; i++){
        if(times[i][0] > max_time){
            max_time = times[i][0]
        }
    }
    return max_time
}

$(function () {

    Highcharts.setOptions({
        global : {
            useUTC : false
        }
    });


    $.getJSON('/data', function(data){

        var param_max_times = {
            'max_time_buyer':0,
            'max_time_seller':0,
            'max_time_user':0
        };
        param_max_times['max_time_buyer'] = find_max_time(data.data_buyer);
        param_max_times['max_time_seller'] = find_max_time(data.data_seller);
        param_max_times['max_time_user'] = find_max_time(data.data_user);


        $('#container').highcharts('StockChart', {
            chart : {
                events : {
                    load : function () {
                        var series_data_buyer = this.series[0],
                            series_data_seller = this.series[1],
                            series_data_user = this.series[2];

                        setInterval(function() {
                            $.getJSON('/data', param_max_times, function(data) {
                                console.log(data);
                                var data_buyer = data.data_buyer,
                                    data_seller = data.data_seller,
                                    data_user = data.data_user;

                                if(data_buyer.length > 0){
                                    console.log(data_buyer);
                                    $.each(data_buyer, function(i, d){
                                        series_data_buyer.addPoint(d, true, true)
                                        console.log(d)
                                    }); 
                                    param_max_times['max_time_buyer'] = find_max_time(data_buyer);
                                }

                                if(data_seller.length > 0){
                                    $.each(data_seller, function(i, d){
                                        series_data_seller.addPoint(d, true, true) 
                                    });
                                    param_max_times['max_time_seller'] = find_max_time(data_seller);
                                }

                                if(data_user.length > 0){
                                    $.each(data_user, function(i, d){
                                        series_data_user.addPoint(d, true, true) 
                                    });
                                    param_max_times['max_time_user'] = find_max_time(data_user);
                                }
                            });
                        },1000 * 10)
                    }
                },
                borderColor: '#EBBA95',
                borderWidth: 2,
                borderRadius: 10
            },

            navigator: {
                adaptToUpdatedData: false,
                handles: {
                    backgroundColor: '#9BCD9B',
                    borderColor: '#9BCD9B'
                },
            },

            legend: {
                enabled: true,
                layout: 'vertical',
                align: 'left',
                verticalAlign: 'top',
                backgroundColor: '#FCFFC5',
                borderColor: 'black',
                borderWidth: 2,
                shadow: true
            },

            rangeSelector: {
                buttonTheme: { // styles for the buttons
                    fill: 'none',
                    stroke: 'none',
                    'stroke-width': 0,
                    r: 8,
                    style: {
                        color: '#039',
                        fontWeight: 'bold'
                    },
                    states: {
                        hover: {
                        },
                        select: {
                            fill: '#039',
                            style: {
                                color: 'white'
                            }
                        }
                    }
                },


                inputBoxBorderColor: 'gray',
                inputBoxWidth: 120,
                inputBoxHeight: 18,
                inputStyle: {
                    color: '#039',
                    fontWeight: 'bold'
                },

                labelStyle: {
                    color: 'silver',
                    fontWeight: 'bold'
                },

                buttons: [{
                    count: 30,
                    type: 'second',
                    text: '30S'
                }, {
                    count: 5,
                    type: 'minute',
                    text: '5M'
                }, {
                    count: 30,
                    type: 'minute',
                    text: '30M'
                }, {
                    count: 1,
                    type: 'day',
                    text: '1D'
                },{
                    count: 2,
                    type: 'day',
                    text: '2D'
                }, {
                    type: 'all',
                    text: 'All'
                }],
                inputEnabled: true,
                selected: 5
            },

            title : {
                text : 'Customer Statics',
                style: {
                    color: '#5CACEE',
                    fontWeight: 'bold'
                }
            },
                
            xAxis: {
                title: {
                    text: 'time'
                },
                type: 'datetime',
                tickPixelInterval: 50
            },

            yAxis: [{
                title: {
                    text: 'value'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            }],

            exporting: {
                enabled: false
            },

            series : [{
                name : 'buyer',
                tooltip: {
                    valueDecimals: 2,
                    valuePrefix: '$',
                    valueSuffix: ' USD'
                },
                data : data.data_buyer

            },{
                name : 'seller',
                tooltip: {
                    valueDecimals: 2,
                    valuePrefix: '%',
                    valueSuffix: ' RMB'
                },
                data : data.data_seller

            },{
                name : 'login_user',
                tooltip: {
                    valueDecimals: 2,
                    valuePrefix: '#',
                    valueSuffix: ' CCC'
                },
                data : data.data_user
            }]
        }
    );
    });
});

你可能感兴趣的:(Highstock+flask+mysql实现多线条动态刷新)