<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestHomeOrder} from 'actions/homeActions';


class MyMonitor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orders: props.orders || []
    }
    this.renderCharts = this.renderCharts.bind(this);
    this.renderOrders = this.renderOrders.bind(this);
  }

  componentWillReceiveProps(props) {
    this.setState({orders: props.orders}, this.renderOrders)
  }

  componentDidMount() {
    this.renderOrders();
  }

  render() {
    return(
      <div className='pb-10'>
        <div id='monitor'></div>
      </div>
    )
  }

  renderOrders() {
    let {orders} = this.state, data1 = [], data2 = [];
    orders.length > 0 && orders.map((item, idx) => {
      let time = item[4] + (8 * 60 * 60 * 1000);
      if(item[3]== 0) {
        // data1.push([time, Math.log(item[1])])
        data1.push({
          x: time,
          y: Math.log(item[1]),
          val: item[1]
        })
      } else if (item[3] == 1) {
        // data2.push([time, Math.log(item[1])])
        data2.push({
          x: time,
          y: Math.log(item[1]),
          val: item[1]
        })
      }
    
    })

    this.renderCharts(data1, data2)


  }

  renderCharts(data1, data2, data3, data4) {
    let formats='%H:%M';
    Highcharts.chart('monitor', {
      chart: {
        type: 'scatter',
        zoomType: 'xy'
      },
      title: {
        text: '24小时转入转出',
        style: {
          fontSize: '14px'
        }
      },
      subtitle: {
        // text: 'Source: Heinz  2003'
      },
      xAxis: {
        title: {
          enabled: true,
          text: 'time (hour)'
        },
        labels: {
          formatter: function() {
            return Highcharts.dateFormat(formats,this.value);
          }
        },
        type: 'datetime',
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true,

      },
      yAxis: {
        title: {
          text: ''
        },
      },
      plotOptions: {
        scatter: {
          marker: {
            radius: 5,
            states: {
              hover: {
                enabled: true,
                lineColor: 'rgb(100,100,100)'
              }
            }
          },
          states: {
            hover: {
              marker: {
                enabled: false
              }
            }
          },
          tooltip: {
            
          }
        }
      },
      tooltip: {
        formatter: function() {
          return `${this.series.name}<br> 数量：${this.point.val}`
        }
      },
      series: [{
        name: '转出',
        color: 'rgba(252, 5, 46, 1)',
        data: data1
    
      }, {
        name: '转入',
        color: '#28a745',
        // color: '#007bff',
        data: data2
      }, 
      ]
    });
  }
}

function mapState(state) {
  return {
    orders: state.homeOrder.orders
  }
}

function mapDispatch(dispatch) {
	return {
		getOrders: () => dispatch(requestHomeOrder())
	}
}

export default connect(mapState, mapDispatch)(MyMonitor);
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-

from flask import Flask,jsonify,request
from api.order import *
from api.address import *
from api.ut_price import *
from api.transaction import *


app = Flask(__name__)


###大单监控
@app.route("/api/v1/monitor/order")
def order():

    order_list = query_big_order()
    return jsonify(order_list)

####地址监控
@app.route("/api/v1/monitor/address")
def address():
    address_list = query_address()
    return jsonify(address_list)

###ut价格
@app.route("/api/v1/monitor/price")
def price():
    period = request.values.get('period')
    price = ut_price(period)
    return jsonify(price)

###交易数度
@app.route("/api/v1/monitor/transaction")
def transaction():
    f = request.values.get('f')
    speed = trans_speed(f)
    return jsonify(speed)

def start():

    print("start web server at 5000")
    app.run(host='0.0.0.0', port=5000)



if __name__ == '__main__':
    start()
<file_sep>/**
 * Created by admin on 2017/4/14.
 */

const initState = {isFetching: true, fetched: false, orders: [],};

export default function homeOrder(state = initState, action) {
	switch (action.type) {
		case 'fetchHomeOrder' :
			return Object.assign({}, state, {isFetching: true, fetched: false});
		case 'reciveHomeOrder':
			return Object.assign({}, state, {isFetching: false, fetched: true, orders: action.orders});
		case 'fetchHomehomeOrderErr':
			return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
		default :
			return state;
	}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import          #如果没有这一行，下一行可能会出错

SQLALCHEMY_DATABASE_URI='mysql://ulord:===passrod===@localhost:3306/tn?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS=True
SQLALCHEMY_POOL_SIZE=10<file_sep>from create_db import *


def query_address():
    row_list = []
    try:
        address_query = "select DATE_FORMAT(create_date,'%Y-%m-%d'),gt10000_address,gt0_address,trans_num,address_num from ud_trans_address where create_date>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -90 DAY),'%Y-%m-%d') and create_date <=DATE_FORMAT(NOW(),'%Y-%m-%d') order by create_date asc"

        res = db.session.execute(address_query)
        row_list = res.fetchall()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print e

    all_address_list = []
    for index in range(len(row_list)):
        address_list = []
        address_list.append(row_list[index][0])
        address_list.append(row_list[index][1])
        address_list.append(row_list[index][2])
        address_list.append(row_list[index][3])
        address_list.append(row_list[index][4])
        all_address_list.append(address_list)

    return all_address_list<file_sep>/**
 * Created by admin on 2017/4/14.
 */

const initState = {isFetching: true, fetched: false, addressList: [],};

export default function addressList(state = initState, action) {
	switch (action.type) {
		case 'fetchAddressList' :
			return Object.assign({}, state, {isFetching: true, fetched: false});
		case 'reciveAddressList':
			return Object.assign({}, state, {isFetching: false, fetched: true, addressList: action.addressList});
		case 'fetchAddressListrErr':
			return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
		default :
			return state;
	}
}<file_sep>/**
 * Created by admin on 2017/4/14.
 */

const initState = {isFetching: true, fetched: false, list: [],};

export default function priceTrend(state = initState, action) {
	switch (action.type) {
		case 'fetchPriceTrend' :
			return Object.assign({}, state, {isFetching: true, fetched: false});
		case 'recivePriceTrend':
			return Object.assign({}, state, {isFetching: false, fetched: true, list: action.list});
		case 'fetchPriceTrendErr':
			return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
		default :
			return state;
	}
}<file_sep>

### python

pip install -r requirements.txt


### UI
    npm install yarn -g
    yarn install
    yarn run build
    webpack.dev.config.js //修改server ip
### 数据库脚本
    sql/ut.sql

### 第一次运行需要同步历史数据(多线程同步数据时间比较长)
    job/config.py //---数据库、守护进程配置文件
    nohup python -u thread_run.py >log_thread.txt 2>&1 &
    
### 同步完历史数据后，使用job_run.py同步数据（单机运行）
    nohup python -u job_run.py >log_job.txt 2>&1 &
    
### app service run
    config.py //---数据库配置文件
    nohup python -u app.py >log_app.txt 2>&1 &
    
    <file_sep>/**
 * Created by admin on 2017/3/3.
 */
import { Router, hashHistory, browserHistory} from 'react-router';
import React from 'react';

// 按需加载
const routers = {
  path:'/',
	getComponent(nextState,callback){
		require.ensure([],require=>{
			callback(null,require('containers/main').default);    // 按需加载时，require不能使用变量，且之前不能使用import将组件引入。如果你的组件是使用es5的module.exports导出的话，那么只需要require('components/Index')即可。而如果你的组件是使用es6的export default导出的话，那么需要加上default
		},'');
	},
  indexRoute:{
	  getComponent(nextState,callback){
		  require.ensure([],require=>{
			  callback(null,require('containers/home').default);
		  },'home');
	  },
  },
  childRoutes:[
    {
      path:'home',
	    getComponent(nextState,callback){
		    require.ensure([],require=>{
			    callback(null,require('containers/home').default);
		    },'home');
	    },
    },
    {
      path:'management',
	    getComponent(nextState,callback){
		    require.ensure([],require=>{
			    callback(null,require('containers/management').default);
		    },'management');
	    },
    }
  ]
};

export default <Router routes={routers} history={hashHistory}/>
// export default <Router routes={routers} history={browserHistory}/>    // 使用browserHistory, 当用户直接请求页面的某个子路由会报404的错误<file_sep>CREATE TABLE `ud_address_details` (
  `Address` varchar(60) DEFAULT NULL,
  `Total_Received` float DEFAULT NULL,
  `Total_Sent` float DEFAULT NULL,
  `Final_Balance` float DEFAULT NULL,
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `update_time` timestamp NULL DEFAULT NULL,
  `trans_no` int(10) DEFAULT NULL,
  `mined_time` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;



CREATE TABLE `ud_block_info` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `height` int(10) DEFAULT NULL,
  `json_date` varchar(5000) DEFAULT NULL,
  `rsync_date` timestamp NULL DEFAULT NULL,
  `date_type` varchar(10) DEFAULT NULL,
  `block_hash` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `ud_block` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `height` int(10) DEFAULT NULL,
  `mined_by` varchar(10) DEFAULT NULL,
  `difficulty` float DEFAULT NULL,
  `transactions_number` int(10) DEFAULT NULL,
  `timestamp` int(11) DEFAULT NULL,
  `Size` int(10) DEFAULT NULL,
  `Bits` varchar(10) DEFAULT NULL,
  `Block_reward` float DEFAULT NULL,
  `Previous_Block` varchar(100) DEFAULT NULL,
  `Next_Block` varchar(100) DEFAULT NULL,
  `BlockHash` varchar(100) DEFAULT NULL,
  `total_trans` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `block_height_index` (`height`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


CREATE TABLE `ud_price` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `price` float DEFAULT NULL,
  `create_time` timestamp NULL DEFAULT NULL,
  `platform` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


CREATE TABLE `ud_trans_address` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `create_date` timestamp NULL DEFAULT NULL,
  `gt10000_address` int(10) DEFAULT NULL,
  `gt0_address` int(10) DEFAULT NULL,
  `trans_num` int(10) DEFAULT NULL,
  `address_num` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `ud_transaction_records` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `HEIGHT` int(10) DEFAULT NULL,
  `TX_ID` varchar(100) DEFAULT NULL,
  `confirmations` int(60) DEFAULT NULL,
  `time` int(10) DEFAULT NULL,
  `blocktime` int(10) DEFAULT NULL,
  `version` int(10) DEFAULT NULL,
  `fees` float DEFAULT NULL,
  `ud_blockid` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


CREATE TABLE `ud_transaction_recods_vin` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `txid` varchar(100) DEFAULT NULL,
  `vout` int(10) DEFAULT NULL,
  `vin_txid` varchar(100) DEFAULT NULL,
  `ud_transaction_recordsid` int(10) NOT NULL,
  `coinbase` varchar(100) DEFAULT NULL,
  `height` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `vout_vin_txid_index` (`vin_txid`),
  KEY `vout_height_index` (`height`),
  KEY `index_vin_txid` (`txid`),
  KEY `index_vin_vout` (`vout`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


CREATE TABLE `ud_transaction_recods_vout` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `value` float DEFAULT NULL,
  `n` int(10) DEFAULT NULL,
  `txid` varchar(100) DEFAULT NULL,
  `ud_transaction_recordsid` int(10) NOT NULL,
  `type` varchar(50) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `mined_time` timestamp NULL DEFAULT NULL,
  `has_vin` int(10) DEFAULT NULL,
  `coinbase` varchar(100) DEFAULT NULL,
  `height` int(10) DEFAULT NULL,
  `has_trans` varchar(10) DEFAULT NULL,
  `mined_day` varchar(30) DEFAULT NULL,
  `trans_value` double DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `vout_txid_index` (`txid`),
  KEY `vout_has_vin_index` (`has_vin`),
  KEY `vout_address_index` (`address`),
  KEY `idx_vout_vin` (`has_vin`),
  KEY `index_vout_mined_day` (`mined_day`),
  KEY `index_vout_height` (`height`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;



CREATE TABLE `ud_transaction_recods_address` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `address` varchar(100) DEFAULT NULL,
  `ud_transaction_recods_voutid` int(10) NOT NULL,
  `current_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `mined_time` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `recods_address_index` (`address`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;<file_sep>import datetime,time
import schedule
from rawtransaction_task import *
from addres_count_task import *
from trans_address_task import *
from crawl_ulord_price_task import *
from trans_block_task import *

def block_job():
    update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print("run crawl_ulord job:", datetime.datetime.now())
    crawl_ulord()
    crawl_price_coin()
    print("run block_check job:", datetime.datetime.now())
    rsync_block()
    print("run address_count job:", datetime.datetime.now())
    address_count_job()
    print("run trans_address_count job:", datetime.datetime.now())
    tran_address_job('')
    print("run trans_block_update job:", datetime.datetime.now())
    trans_block_update()







if __name__ == '__main__':
    print('job run...')
    schedule.every(10).minutes.do(block_job)
    while True:
        beginTime = datetime.datetime.now()
        print('block_job run...', beginTime)
        schedule.run_pending()
        time.sleep(60)<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import { isArray } from 'util';

class AreaChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
        largeAccount: [],
        nonZeroAccount: [],
        activityAccount: [],
        totalAccount: [],
        categories: [],
        pointStart: ''
    }
    this.renderCharts = this.renderCharts.bind(this);
  }

  render() {
    return(
        <div className='area-container'>
            <div id='large-container'></div>
            <div className='white-space'></div>
            <div id='account-container'></div>
            <div className='white-space'></div>
            <div id='activity-container'></div>
        </div>
    )
  }

  componentWillReceiveProps(newProps) {
    if(newProps.addressList && newProps.addressList instanceof Array) {
        let addressList = newProps.addressList, largeAccount = [], totalAccount = [], activityAccount = [], nonZeroAccount = [], categories = [], pointStart = addressList[0][0];
        addressList.length > 0 && addressList.map( (item, idx) => {
        largeAccount.push(item[1]);
        nonZeroAccount.push(item[2])
        activityAccount.push(item[3]);
        totalAccount.push(item[4]);
        categories.push(item[0])
        })

        this.setState({largeAccount, nonZeroAccount, activityAccount, totalAccount, pointStart, categories}, this.renderCharts)
    }
  }

  componentDidMount() {
    this.renderCharts()
  }

  renderCharts() {      
    let {largeAccount, nonZeroAccount, activityAccount, totalAccount, categories, pointStart} = this.state;
    let chart1 = Highcharts.chart('account-container',{
        chart: {
            type: 'area'
        },
        title: {
            text: '账户数统计'
        },
        xAxis: {
            allowDecimals: false,
            categories: categories
        },
        yAxis: {
            title: {
                text: ''
            },
        },
        tooltip: {
          //   pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
        },
        
        series: [{
            name: '非零账户数',
            color: '#77a2c5',
            data: nonZeroAccount
        }, {
            name: '账户总数',
            color: '#a4c1d8',
            data: totalAccount 
        }]
    });

    let chart2 = Highcharts.chart('activity-container',{
        chart: {
            type: 'area'
        },
        title: {
            text: '活跃账户数'
        },
        xAxis: {
            allowDecimals: false,
            categories: categories
        },
        yAxis: {
            title: {
                text: ''
            },
        },
        tooltip: {
          //   pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
        },
        
        series: [{
            name: '活跃账户数',
            color: '#a4c1d8',
            data: activityAccount 
        }]
    });

    let chart3 = Highcharts.chart('large-container',{
        chart: {
            type: 'area'
        },
        title: {
            text: '大户账户'
        },
        xAxis: {
            allowDecimals: false,
            categories: categories
        },
        yAxis: {
            title: {
                text: ''
            },
        },
        tooltip: {
          //   pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
        },
        
        series: [{
            name: '大户账户数',
            color: '#a4c1d8',
            data: largeAccount 
        }]
    });
  }
}


function mapState(state) {
  return {
    addressList: state.addressList.addressList
    // orders: state.homeOrder.orders
  }
}

function mapDispatch(dispatch) {
	return {
		// getOrders: () => dispatch(requestHomeOrder())
	}
}

export default connect(mapState, mapDispatch)(AreaChart);<file_sep>/*
	webpack将所有的文件当作js文件来处理，主要是通过一个入口文件，查找相应的依赖，遇见不是js的文件借助相应的loader来进行处理，打包输出到统一的js文件中。
	webpack基于模块化打包的工具。同时它的核心功能有许多的插件以及loader，来处理我们的文件。
*/

const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
	entry: {
		vendor: ['react', 'react-dom'],
		index: path.resolve(__dirname, "src/index.js")
	},
	output: {
		path: path.resolve(__dirname, "dist/"),    // 打包好的文件输出的路径
		filename: "js/[name].[hash:8].js",
		// publicPath: "/dist",                  // 指定 HTML 文件中资源文件 (字体、图片、JS文件等) 的文件名的公共 URL 部分的
		chunkFilename: 'js/[name].[hash:8].js'      // 按需加载时打包的chunk
	},
	module: {
		rules: [
			{
				test: /.(js|jsx)$/,
				use: [{
					loader: 'babel-loader',
					options: {presets: ["react", ["env", {"modules": false}]]}
				}],
				exclude: path.resolve(__dirname, "node_modules")  // 排除node_modules下的文件
			},
			{
				test: /\.css$/,
				exclude: /node_modules/,
				use: [
					"style-loader",
					"css-loader",
				]
			},
			{
				test: /\.less$/,
				exclude: /node_modules/,
				use: [
					"style-loader",
					"css-loader",
					"less-loader"
				]
			},
			{
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
					"style-loader",
					"css-loader",
					"sass-loader"
				]
      },
			{
				test: /\.(gif|png|jpe?g)$/,
				use: [{
					loader: "file-loader",
					options: {
						name: "static/img/[name].[ext]"
					}
				}]
			},
			{
				test: /\.(ttf|eot|svg|woff)(\?(\w|#)*)?$/,
				use: [{
					loader: "file-loader",
					options: {
						name: "static/font/[name].[ext]"
					}
				}]
			}
		]
	},
	resolve: {
		modules:[path.resolve(__dirname,'src'),'node_modules'],   // 将src添加到搜索目录，且src目录优先'node_modules'搜索。modules: [],告诉 webpack 解析模块时应该搜索的目录.默认为node——modules
		extensions: [".js", ".jsx", ".css", ".less", '.scss'],    // 自动解析确定的扩展名（js/jsx/json),能够使用户在引入模块时不带扩展
		alias: {                                                  // 创建 import 或 require 的别名，来确保模块引入变得更简单
			"components": path.resolve(__dirname, 'src/components/'),
			"containers": path.resolve(__dirname, 'src/containers/'),
			"assets": path.resolve(__dirname, "src/assets/"),
			"actions": path.resolve(__dirname, 'src/actions/'),
			"reducers": path.resolve(__dirname, 'src/reducers/'),
			"utils": path.resolve(__dirname, 'src/utils/'),
		}
	},
	plugins: [
		require('autoprefixer'),    // 自动补全css前缀
		new htmlWebpackPlugin({     // 自动创建html
			template: 'index.html',   // 创建html所引用的模板，默认为根目录下的html
			title: "",  							// 传参，模板中可通过<%= htmlWebpackPlugin.options.title%>来获取
			filename: "index.html",   // 创建后的html的文件名
			// inject: true           // 注入打包好的js,默认为true。 可通过  inject: head/body  声明将js注入到模板中的head/body标签中
		}),
		new webpack.optimize.CommonsChunkPlugin(['vendor']),  // 将公用的模块抽取到vendor文件中
		new CleanWebpackPlugin('dist/', { verbose: false }),    // 每次打包时，将之前打包生成的文件都删除
		new webpack.optimize.UglifyJsPlugin({                 // 压缩打包的js文件
			sourceMap: true,                                    // 当你的js编译压缩后，需要继续读取原始脚本信息的行数，位置，警告等有效调试信息时,手动开启UglifyJsPlugin 的配置项：sourceMap: true
			compress: {
				warnings: false
			}
		}),
		new webpack.ProvidePlugin({ // 配置全局的jquery
			$:"jquery",
			jQuery:"jquery",
			"window.jQuery":"jquery"
		})
	],
};<file_sep># -*- coding: utf-8 -*-
"""
@Author: <NAME>(050511)
"""

import requests,os,time,datetime,json
import sys

from lxml import etree
from job_create_db import *

reload(sys)
sys.setdefaultencoding('utf8')


def crawl_price_coin():
    try:
        sp = time.time()
        st = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp))
        etl_time = datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
        target_url = "https://www.aicoin.net.cn/api/second/global_custom?symbol=kucoinuteth&list_flag=2"
        headers = {"Accept": "*/*",
                   "Accept-Encoding": "gzip, deflate, br",
                   "Accept-Language": "zh-CN,zh;q=0.9",
                   "Connection": "keep-alive",
                   "Cookie": "_ga=GA1.3.56640674.1537171331; Hm_lvt_3c606e4c5bc6e9ff490f59ae4106beb4=1537171331,1537171419,1537171773; acw_tc=784c10e115378666792501369ed44e4f9808ab78a3b64d96ac3260bc4abf69; _gid=GA1.3.1697212968.1537866685; Hm_lpvt_3c606e4c5bc6e9ff490f59ae4106beb4=1537868855; _gat_gtag_UA_108140256_2=1; XSRF-TOKEN=<KEY>%3D%3D; aicoin_session=<KEY>",
                   "Host": "www.aicoin.net.cn",
                   "Referer": "https://www.aicoin.net.cn/",
                   "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
        r = requests.get(target_url, headers=headers)
        d = r.text

        data = json.loads(d)
        price_data_list = data["quotes"]
        price_info_list = []

        for price_data in price_data_list:
            price = price_data["last_curr"]
            currency_base = price_data["currency_base"]
            if currency_base == "lbanketh":
                currency_name = "UT/ETH(LBank)"
            elif currency_base == "kucoineth":
                currency_name = "UT/ETH(Kucoin)"
            elif currency_base == "kucoinbtc":
                currency_name = "UT/BTC(Kucoin)"
            else:
                currency_name = "UT/ETH(BBX)"
            price_info = (currency_name, price, etl_time)
            price_info_list.append(price_info)

            sql = "insert into ud_price (create_time,price,platform) VALUES (DATE_FORMAT(NOW(),   '%%Y-%%m-%%d %%H:%%i'),'%s','%s')" % \
                  (price, currency_name)
            print sql
            res = db.session.execute(sql)

        db.session.commit()

    except Exception as e:
        db.session.rollback()
        print(e)

def crawl_ulord():
    try :

        #获取当前时间
        os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
        time_now = int(time.time())
        #转换成localtime
        time_local = time.localtime(time_now)
        #转换成新的时间格式(2016-05-09 18:59:20)
        etl_time = time.strftime('"%Y-%m-%d %H:%M:%S"',time_local)
        url = "http://www.topbtc.one/"
        headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Cookie": "PHPSESSID=jna61tcaorgat5o41nd08d6i46; _ga=GA1.2.1660271731.1529467228; _gid=GA1.2.1811285768.1529467228; _gat=1; SERVERID=90f486e728e39041f7d76ebd13f977d3|1529467248|1529467225",
        "Host": "www.topbtc.one",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"}
        r = requests.get(url,headers=headers)
        d = r.text
        html = etree.HTML(d)
        coinname = html.xpath("//div[@id='ETHMarket']/table/tbody/tr/td[2]/text()")
        coinname = ["".join(name.split()) for name in coinname]

        price_list = html.xpath("//div[@id='ETHMarket']/table/tbody/tr/td[3]/span/text()")
        price_list = [price.replace("/¥","")for price in price_list]

        info = (etl_time,price_list)
        dict_list = dict(zip(coinname,price_list))

        for name in coinname:
            if "(UT/ETH)" in name:
                target_key = name
        price = dict_list[target_key]


        # 创建连接

        sql = "insert into ud_price (create_time,price,platform) VALUES (DATE_FORMAT(NOW(),   '%%Y-%%m-%%d %%H:%%i'),'%s','%s')" % \
              (price,'topbtc')
        print sql

        res = db.session.execute(sql)
        db.session.commit()
    except Exception as e:
      db.session.rollback()
      print(e)



<file_sep>const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// 读取同一目录下的 base config
const config = require('./webpack.base.config');

config.plugins.push(
	// 官方文档推荐使用下面的插件确保 NODE_ENV
	new webpack.DefinePlugin({
		'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
	}),
	// 启动 minify
	new webpack.LoaderOptionsPlugin({ minimize: true })
	// 抽取 CSS 文件
	// new ExtractTextPlugin({
	// 	filename: '[name].css',
	// 	allChunks: true,
	// 	ignoreOrder: true
	// })
);

module.exports = config;<file_sep>from flask import Flask
from create_db import *

def query_big_order():
    row_list = []
    try :
       # big_order_query = " select address,value,DATE_FORMAT(mined_time,   '%Y-%m-%d %H:%i:%S'),has_vin,UNIX_TIMESTAMP(mined_time)*1000 from ud_transaction_recods_vout  where CHAR_LENGTH(address)>10  and `value`>500 and mined_time>DATE_FORMAT(Now(),'%Y-%m-%d') order by mined_time desc  "
        big_order_query = "select * from (select address,value,DATE_FORMAT(mined_time,   '%Y-%m-%d %H:%i:%S'),has_vin,UNIX_TIMESTAMP(mined_time)*1000,mined_time from ud_transaction_recods_vout  where `value`>500 and `has_trans`=0 and (mined_day=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -24 HOUR),  '%Y-%m-%d') or mined_day=DATE_FORMAT(NOW(),   '%Y-%m-%d')) order by mined_time desc ) a where a.mined_time>DATE_ADD(NOW(),INTERVAL -24 HOUR)"

        res = db.session.execute(big_order_query)
        row_list = res.fetchall()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print e

    order_list = []
    for index in range(len(row_list)):
        list = []
        list.append(row_list[index][0])
        list.append(row_list[index][1])
        list.append(row_list[index][2])
        list.append(row_list[index][3])
        list.append(row_list[index][4])
        order_list.append(list)

    return order_list<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestTransList} from 'actions/transAction';

class Transaction extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      period: 'hour',
      categories: []
    }
    this.renderTrend = this.renderTrend.bind(this);
    this.changePeriod = this.changePeriod.bind(this);

  }

  changePeriod(period) {
    let {getTransData} = this.props;
    this.setState({
      period
    })
    getTransData(period)
  }

  render() {
    let {period} = this.state;

    return (
      <div>
        <p className='change-period-tab'>
          <span className={`${period === 'hour'? 'active': '' }`} onClick={() => this.changePeriod('hour')}>每时</span>
          <span className={`${period === 'day'? 'active': '' }`} onClick={() => this.changePeriod('day')}>每天</span>
          <span className={`${period === 'week'? 'active': '' }`} onClick={() => this.changePeriod('week')}>每周</span>
          <span className={`${period === 'month'? 'active': '' }`} onClick={() => this.changePeriod('month')}>每月</span>
        </p>
        <div id='trans-container'></div>
        <p className='trans-label'>交易速度</p>
      </div>
    )
  }

 
  componentWillReceiveProps(newProps) {
    let {period} = this.state;
    let transData = newProps.transData, categories = [], data = [];
    transData.length > 0 && transData.map( (item, idx) => {
      if(period === 'month') {
        let month = item[1].split('-')[0]+ '-' + item[1].split('-')[1];
        categories.push(month)
      } else if (period === 'day') {
        let day = item[1].split('-')[0] + '-' + item[1].split('-')[1] + '-' + item[1].split('-')[2].split(' ')[0];
        categories.push(day);
      } else if(period === 'week') {
        let temp = ''
        switch(item[0]) {
          case 'Monday':
            temp = '星期一';
            break;
          case 'Tuesday':
            temp = '星期二';
            break;
          case 'Wednesday':
            temp = '星期三';
            break;
          case 'Thursday':
            temp = '星期四';
            break;
          case 'Friday':
            temp = '星期五';
            break;
          case 'Saturday':
            temp = '星期六';
            break;
          case 'Sunday':
            temp = '星期天';
            break;
          
        }
        categories.push(temp)
      } else if(period === 'hour') {
        let hour =item[1].split('-')[2].split(' ')[1] + ':00';
        categories.push(hour)
      }
      data.push( { y: Number(item[6]), trans_num: item[2], total_block: item[3], total_block_size: item[5], speed: item[6]});
    })
    this.setState({categories, data}, this.renderTrend)
  }

  componentDidMount() {
    this.renderTrend();
  }

  renderTrend() {
    let { categories, data, format, tickInterval} = this.state;  
    Highcharts.chart('trans-container', {
    
      title: {
        text: '',
      },
      xAxis: {
        categories: categories,
      },
      yAxis: {
        title: {
          text: ''
        },
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true,
      },
      legend: {
        enabled: false
      },
      tooltip: {
        pointFormat: 'Total Transaction: {point.trans_num}<br/>Total block: {point.total_block}<br/>avg blockSize: {point.total_block_size}<br>Transaction Speed: {point.speed}'
      },
      series: [{
        name: '交易速度',
        data: data,
      }]
    });
    
  }
}

function mapState(state) {
  return {
    transData: state.transListReducer.transList
  }
}

function mapDispatch(dispatch) {
	return {
		getTransData: (period) => dispatch(requestTransList(period)),
  }
}

export default connect(mapState, mapDispatch)(Transaction);<file_sep>from job import db

class ud_transaction_recods_addr(db.Model):
    __tablename__ = 'ud_transaction_recods_addr'
    id = db.Column(db.Integer, primary_key=True)
    address = db.Column(db.String(100), nullable=True)
    current_date = db.Column(db.TIMESTAMP(True), nullable=True)
    ud_transaction_recods_voutid = db.Column(db.Integer, nullable=True)

    def __init__(self, address):
        self.address = address

    def __repr__(self):
        return '<ud_transaction_recods_addr %r>'

class ud_transaction_recods_vout(db.Model):
    __tablename__ = 'ud_transaction_recods_vout'
    id = db.Column(db.Integer, primary_key=True)
    height = db.Column(db.Integer, nullable=True)
    txid = db.Column(db.String(True), nullable=True)
    value = db.Column(db.Float, nullable=True)
    n = db.Column(db.Integer, nullable=True)
    ud_transaction_recordsid = db.Column(db.Integer, nullable=True)
    type = db.Column(db.String(50), nullable=True)
    address = db.Column(db.String(100), nullable=True)
    mined_time = db.Column(db.TIMESTAMP(True), nullable=True)
    has_vin = db.Column(db.String(100), nullable=True)
    coinbase = db.Column(db.String(100), nullable=True)

    def __init__(self, height):
        self.height = height

    def __repr__(self):
        return '<ud_transaction_recods_vout %r>'

class ud_transaction_recods_vin(db.Model):
    __tablename__ = 'ud_transaction_recods_vin'
    id = db.Column(db.Integer, primary_key=True)
    height = db.Column(db.Integer, nullable=True)
    txid = db.Column(db.String(True), nullable=True)
    vout = db.Column(db.Integer, nullable=True)
    vin_txid = db.Column(db.String(100), nullable=True)
    ud_transaction_recordsid = db.Column(db.Integer, nullable=True)
    coinbase = db.Column(db.String(100), nullable=True)


    def __init__(self, height):
        self.height = height

    def __repr__(self):
        return '<ud_transaction_recods_vin %r>'

class ud_transaction_records(db.Model):
    __tablename__ = 'ud_transaction_records'
    id = db.Column(db.Integer, primary_key=True)
    height = db.Column(db.Integer, nullable=True)
    tx_id = db.Column(db.String(True), nullable=True)
    confirmations = db.Column(db.Integer, nullable=True)
    time = db.Column(db.Integer, nullable=True)
    blocktime = db.Column(db.Integer, nullable=True)
    version = db.Column(db.Integer, nullable=True)
    fees = db.Column(db.Float, nullable=True)
    ud_blockid = db.Column(db.Integer, nullable=True)

    def __init__(self,height):
        self.height = height

    def __repr__(self):
        return '<ud_transaction_records %r>'

class udBlock(db.Model):
    __tablename__ = 'ud_block'
    id = db.Column(db.Integer, primary_key=True)
    height = db.Column(db.Integer, nullable=True)
    mined_by = db.Column(db.TIMESTAMP(True), nullable=False)
    difficulty = db.Column(db.Float, nullable=True)
    transactions_number = db.Column(db.Integer, nullable=True)
    timestamp = db.Column(db.TIMESTAMP(True), nullable=True)
    Size = db.Column(db.Integer, nullable=True)
    Bits = db.Column(db.String(10), nullable=True)
    Block_reward = db.Column(db.Float, nullable=True)
    Previous_Block = db.Column(db.String(100), nullable=True)
    Next_Block = db.Column(db.String(100), nullable=True)
    BlockHash = db.Column(db.String(100), nullable=True)

    def __init__(self,height, mined_by, difficulty, transactions_number, timestamp, size, bits, block_reward, previous_block, next_block, blockHash):
        self.height = height
        self. mined_by=mined_by
        self.difficulty=difficulty
        self.transactions_number=transactions_number
        self.timestamp=timestamp
        self.size=size
        self.bits=bits
        self.block_reward=bits
        self.previous_block=previous_block
        self.next_block=next_block
        self.blockHash=blockHash

    def __repr__(self):
        return '<ud_block %r>'


class ud_trans_address(db.Model):
    __tablename__ ='ud_trans_address'
    id = db.Column(db.Integer, primary_key=True)
    ut_num = db.Column(db.Integer, nullable=True)
    ut_balance_num = db.Column(db.Integer,nullable=True)
    trans_num = db.Column(db.Integer,nullable=True)
    address_num = db.Column(db.Integer,nullable=True)
    create_date = db.Column(db.TIMESTAMP(True),nullable=False)

    def __repr__(self):
        return '<ud_trans_address %r>'

    def __init__(self,ut_num,ut_balance_num,trans_num,address_num,create_date):
        self.ut_num = ut_num
        self.ut_balance_num = ut_balance_num
        self.trans_num = trans_num
        self.address_num = address_num
        self.create_date = create_date<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *
import traceback

###账户数量统计


def trans_block_count(height):
  try:


      trans_query_sql = "select count(1) from ud_transaction_recods_vout where height=%s and `has_trans`=0" % \
                          (height)

      res = db.session.execute(trans_query_sql)
      trans_count = res.fetchone()


      trans_address_update_sql = "update ud_block set total_trans=%s  where height=%s" % \
                                     (trans_count[0],height)
      db.session.execute(trans_address_update_sql)
      db.session.commit()
  except Exception as e:
      db.session.rollback()
      traceback.print_exc()






def trans_block_update():
    try:

        trans_query_sql = "select height from ud_block where total_trans is null"

        res = db.session.execute(trans_query_sql)
        height_list = res.fetchall()
        db.session.commit()
        for index in range(len(height_list)):
            trans_block_count(height_list[index][0])
    except Exception as e:
        db.session.rollback()
        traceback.print_exc()


<file_sep>/**
 * Created by admin on 2017/4/14.
 */

import {get} from 'utils/fetch';


export function fetchHomeOrder() {
	return {
		type: 'fetchHomeOrder',
	}
}

export function reciveHomeOrder(orders) {
	return {
		type: 'reciveHomeOrder',
		orders,
	}
}

export function fetchHomeOrderErr(err) {
	return {
		type: 'fetchHomeOrderErr',
		err,
	}
}


export function requestHomeOrder() {
	return dispatch => {
		dispatch(fetchHomeOrder());

		get(`/api/v1/monitor/order`).then(res => {
			dispatch(reciveHomeOrder(res.data));
		})
			.catch(err => {
				console.log(err);
				dispatch(fetchHomeOrderErr(err))
			})
	}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *

###


def address_count(address):
    try:
            update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')


            vout_query_sql ="select  sum(value) as Total_Received, count(*) as trans_no, address, (select  sum(value) from ud_transaction_recods_vout where address =vout.address and has_vin=0) as Final_Balance, (select  sum(value) from ud_transaction_recods_vout where address =vout.address and has_vin=1 ) as Total_Sent, max(vout.mined_time)  from ud_transaction_recods_vout  vout  where  address='%s'  group by address" % \
                            (address)
            print vout_query_sql
            res = db.session.execute(vout_query_sql)
            address_value = res.fetchall()

            Total_Received=address_value[0][0]
            if Total_Received == None:
                Total_Received = 0

            trans_no = address_value[0][1]
            if trans_no == None:
                trans_no = 0

            Final_Balance = address_value[0][3]
            if Final_Balance == None:
                Final_Balance = 0

            Total_Sent=address_value[0][4]
            if Total_Sent == None:
                Total_Sent=0

            address_detail_query_sql = "select * from ud_address_details where address='%s'" % \
                                       (address)
            res = db.session.execute(address_detail_query_sql)
            addr = res.fetchone()
            if addr == None:

                address_detail_insert_sql = "insert into ud_address_details(Address , Total_Received, Total_Sent, Final_Balance, update_time, trans_no) VALUES('%s','%s','%s','%s',DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s')" % \
                                        (address , Total_Received, Total_Sent, Final_Balance, update_time, trans_no)
                db.session.execute(address_detail_insert_sql)
            else :
                address_detail_update_sql = "update ud_address_details set  Total_Received='%s', Total_Sent='%s', Final_Balance='%s', update_time=DATE_FORMAT('%s','%%Y-%%m-%%d'), trans_no='%s'  where address='%s'" % \
                                            (Total_Received, Total_Sent, Final_Balance, update_time, trans_no,address)
                db.session.execute(address_detail_update_sql)

            address_delete_sql = "delete from ud_transaction_recods_address where address='%s'" % \
                                    (address)
            db.session.execute(address_delete_sql)
            db.session.commit()
    except Exception as e:
        db.session.rollback()
        print str(e)
    finally:
        print('finally count_address',address,update_time)

def query_address():
    address_query_sql = "select address  from ud_transaction_recods_address group by address"
    res = db.session.execute(address_query_sql)
    addressList = res.fetchall()
    return addressList

def address_count_job():
    try:
        addressList = query_address()
        for index in range(len(addressList)):
            address=addressList[index][0]
            address_count(address)

    except Exception as e:
        db.rollback()
        print str(e)
    finally:
        print('finally count_address')





<file_sep>测试环境部署方式

## 安装yarn
  npm install yarn -g

## 本地启动
	yarn install

	yarn start

	


## 项目打包方法
	项目初始化（只需执行一次） 
	yarn install


	之后每次重新打包只需执行
		1. yarn run build

	build完之后网站所有文件都会生成在dist文件夹,直接访问 index.html<file_sep>import React, { Component } from 'react';
import {Table} from 'react-bootstrap';
import { connect } from 'react-redux';


class AddressTable extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let {addressList} = this.props, lastAddressData = addressList && addressList[addressList.length -1] || [];
    return(
      <div className='monitor-table-container pd-5'>
        <Table responsive>
         {/* <thead> */}
           {/* <tr>
           <th colSpan="2">地址监控</th>
           </tr> */}
            
          {/* </thead> */}
          <tbody className='monitor-table-body'>
            <tr>     
                <th>项目</th>
                <th>数量</th>
              </tr>
            <tr>
              <td>
                <p>大账户地址</p>
                <p className='small-size'>大于10000UT的账户数量</p>
              </td>
              <td>{lastAddressData[1]}</td>
            </tr>

            <tr>
              <td>
                <p>账户数量统计</p>
                <p className='small-size'>有余额账户数量</p>
              </td>
              <td>{lastAddressData[2]}</td>
            </tr>

            <tr>
              <td>
                <p>活跃地址</p>
                <p className='small-size'>近7天有交易的账户数量</p>
              </td>
              <td>{lastAddressData[3]}</td>
            </tr>
          
          </tbody>
        </Table>
        </div>
      
    )
  }


}

function mapState(state) {
  return {
    addressList: state.addressList.addressList
  }
}


export default connect(mapState, null)(AddressTable);
<file_sep>/**
 * Created by admin on 2017/4/14.
 */

import {get} from 'utils/fetch';


export function fetchPriceTrend() {
	return {
		type: 'fetchPriceTrend',
	}
}

export function recivePriceTrend(list) {
	return {
		type: 'recivePriceTrend',
		list,
	}
}

export function fetchPriceTrendErr(err) {
	return {
		type: 'fetchPriceTrendErr',
		err,
	}
}


export function requestPriceTrend(period) {
	return dispatch => {
		dispatch(fetchPriceTrend());

		get(`/api/v1/monitor/price?period=${period}`).then(res => {
			dispatch(recivePriceTrend(res.data));
		})
			.catch(err => {
				console.log(err);
				dispatch(fetchPriceTrendErr(err))
			})
	}
}<file_sep>from flask import Flask
from create_db import *

def ut_price(period):
    row_list = []
    try:
        ud_price_query = ''
        if period == 'day':
            ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d %h:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -1 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d %h') order by create_time asc"
        elif period == 'week':
            ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d %h:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -7 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d %h') order by create_time asc"
        elif period == 'month':
            ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d 00:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -30 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d') order by create_time asc"

        res = db.session.execute(ud_price_query)
        row_list = res.fetchall()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print e

    price_list = []
    if row_list != None:

        for index in range(len(row_list)):
            list = []
            list.append(row_list[index][0])
            list.append(row_list[index][1])
            price_list.append(list)


    return price_list<file_sep>alabaster==0.7.11
amqp==2.3.2
Babel==2.6.0
billiard==3.5.0.4
celery==4.2.1
certifi==2018.4.16
chardet==3.0.4
click==6.7
docutils==0.14
Flask==1.0.2
Flask-SQLAlchemy==2.1
Foundations==2.1.0
futures==3.2.0
idna==2.7
imagesize==1.0.0
itsdangerous==0.24
Jinja2==2.10
kombu==4.2.1
linecache2==1.0.0
Manager==2.0.5
MarkupSafe==1.0
mysql==0.0.1
mysql-connector-python==8.0.11
Oncilla==0.1.0
order==0.1.17
packaging==17.1
protobuf==3.6.0
py-mysql==1.0
Pygments==2.2.0
pyparsing==2.2.0
pytz==2018.5
requests==2.19.1
schedule==0.5.0
scinum==0.2.3
six==1.11.0
snowballstemmer==1.2.1
Sphinx==1.7.6
sphinx-rtd-theme==0.4.1
sphinxcontrib-websupport==1.1.0
SQLAlchemy==1.2.10
traceback2==1.4.0
typing==3.6.4
unittest2==1.1.0
urllib3==1.23
vine==1.1.4
Werkzeug==0.14.1
lxml==4.2.4
<file_sep># !/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime,time
import concurrent.futures,threading
from rawtransaction_task import *
from addres_count_task import *
from trans_address_task import  *
from job_create_db import *
from trans_block_task import *


def rsync_block(height) :
        print('====rsync_block############################====',threading.current_thread().getName(), height)
        block_load(height)

def rsync_address(address):
        print('====rsync_address############################====', threading.current_thread().getName(), address)
        address_count(address)
def update_vin_trans():
    address_query_sql = "select height from ud_block"
    res = db.session.execute(address_query_sql)
    heightList = res.fetchall()

    for d in range(len(heightList)):
        height = heightList[d][0]
        update_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (SELECT * FROM ud_transaction_recods_vin WHERE vin_txid is not null and height is not null and height='%s') AS a2 SET a1.has_vin = 1 where a1.txid = a2.vin_txid and a1.n=a2.vout" % \
                     (height)
        db.session.execute(update_sql)

        # has_trans 0交易；1挖矿奖励；2找零；
        update_vout_trans_sql = "UPDATE ud_transaction_recods_vout AS a1  INNER JOIN (select distinct vout.txid,vout.address from ud_transaction_recods_vout vout left join  ud_transaction_recods_vin vin on vout.txid=vin.txid left join ud_transaction_recods_vout vout2 on vout2.txid=vin.vin_txid and vin.vout=vout2.n  where  vout.height='%s'  and vout.address=vout2.address ) AS a2 SET a1.`has_trans`=2 where a1.txid=a2.TXID and a1.address=a2.address" % \
                                (height)
        db.session.execute(update_vout_trans_sql)

        if d % 1000 == 0 or (d + 1) == len(heightList):
            print("height", d, len(heightList))
            db.session.commit()
def block_thread():
        endHeight = load_height()
        # 线程池执行
        start_time_1 = time.time()
        with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
                futures = [executor.submit(rsync_block, item) for item in range(endHeight)]
                for future in concurrent.futures.as_completed(futures):
                        print('====block==========', future.result())
        print ("block Thread pool execution in " + str(time.time() - start_time_1), "seconds")



def address_thread():


                addressList = query_day_address()
                if len(addressList)>0:
                        start_time_1 = time.time()
                        with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
                                futures = [executor.submit(rsync_address, addressList[item][0]) for item in range(len(addressList))]
                                for future in concurrent.futures.as_completed(futures):
                                        print('====address==========', future.result())
                        print ("address Thread pool execution in " + str(time.time() - start_time_1), "seconds")

def query_day_address():

     address_query_sql = "select address from ud_transaction_recods_vout vout  group by address"
     res = db.session.execute(address_query_sql)
     addressList = res.fetchall()
     return addressList

def days(str1,str2):
    date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
    date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
    num=(date1-date2).days
    return num

def day_run():
        block_begin_time = "2018-05-22 23:59:59"
        curr_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        #两个日期相隔天数
        day_num = days(curr_time,block_begin_time)
        #
        d1 = datetime.datetime.strptime(block_begin_time, '%Y-%m-%d %H:%M:%S')

        for d in range(0, day_num):
                curr_d = d1 + datetime.timedelta(d)
                tran_address_job(curr_d)

if __name__ == "__main__":
        block_thread()
        update_vin_trans()
        trans_block_update()
        address_thread()
        day_run()




<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-

from json import dumps, loads
from requests import request
import time
from job_create_db import *
from config import *


url = ULORD_IP
auth=(ULORD_USER, ULORD_PASSWORD)



def rsync_block():
    endHeight = load_height()

    max_height_query = "select max(HEIGHT) from ud_block"
    result = db.session.execute(max_height_query)
    max_height = result.fetchone()

    if max_height[0] != None :
        max_height=max_height[0]+1
    else:
        max_height = 1
    count = 0
    try:
        while True:
            height =max_height+count
            print('=================',height)
            block_load(height)


            update_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (SELECT * FROM ud_transaction_recods_vin WHERE vin_txid is not null and height='%s') AS a2 SET a1.has_vin = 1 where a1.txid = a2.vin_txid and a1.n=a2.vout" % \
                         (height)
            db.session.execute(update_sql)

            #has_trans 0交易；1挖矿奖励；2找零；
            update_vout_trans_sql = "UPDATE ud_transaction_recods_vout AS a1  INNER JOIN (select distinct vout.txid,vout.address from ud_transaction_recods_vout vout left join  ud_transaction_recods_vin vin on vout.txid=vin.txid left join ud_transaction_recods_vout vout2 on vout2.txid=vin.vin_txid and vin.vout=vout2.n  where  vout.height='%s'  and vout.address=vout2.address ) AS a2 SET a1.`has_trans`=2 where a1.txid=a2.TXID and a1.address=a2.address" % \
                                    (height)
            db.session.execute(update_vout_trans_sql)
            db.session.commit()

            #找零地址实际交易金额
           # trans_2_query = ""

            if height == endHeight:
                break;
            else:
                count = count+1
    except Exception as e:
        print('error',e)

def save_transaction(txList,ud_blockid):
    for index in range(len(txList)):
        tx = txList[index]
        payload = dumps({"method": 'getrawtransaction', "params": [tx, 1]})
        response = request("POST", url, data=payload, auth=auth)

        res = loads(response.text)
        HEIGHT = res['result']['height']
        TX_ID = res['result']['txid']
        confirmations = res['result']['confirmations']
        time = res['result']['time']
        blocktime = res['result']['blocktime']
        version = res['result']['version']
        fees = 0

        insert_ud_transaction_records_sql = "INSERT INTO ud_transaction_records(HEIGHT, TX_ID , confirmations , time , blocktime , version , fees , ud_blockid ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                                            (HEIGHT,TX_ID, confirmations, time, blocktime, version, fees, ud_blockid)
        result = db.session.execute(insert_ud_transaction_records_sql)

        ud_transaction_recordsid = result.lastrowid
        mined_time = timestamp_to_date(time)
        ###vout
        vout = res['result']['vout']

        ##挖矿奖励
        coinbase = ""
        has_trans = 0
        try:
            coinbase = res['result']['vin'][0]['coinbase']
            has_trans = 1
        except Exception as e:
            coinbase = ""

        for index in range(len(vout)):
            value = vout[index]['value']
            n = vout[index]['n']
            vout_type = vout[index]['scriptPubKey']['type']
            address = vout[index]['scriptPubKey']['addresses'][0]



            insert_ud_transaction_recods_vout_sql = "INSERT INTO ud_transaction_recods_vout(value, n , txid , ud_transaction_recordsid,type,address,mined_time,coinbase,height,has_trans,has_vin,mined_day,trans_value) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s',DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s')" % \
                                                (value, n, TX_ID, ud_transaction_recordsid,vout_type,address,mined_time,coinbase,HEIGHT,has_trans,0,mined_time,value)
            result = db.session.execute(insert_ud_transaction_recods_vout_sql)
            vout_id = result.lastrowid
            try:

                #####vout address
                if vout_type == 'pubkeyhash':
                    addresses = vout[index]['scriptPubKey']['addresses']
                    for index in range(len(addresses)):
                        addr = addresses[index]
                        insert_ud_transaction_recods_address_sql = "INSERT INTO ud_transaction_recods_address(address,ud_transaction_recods_voutid,mined_time) VALUES ('%s', '%s','%s')" % \
                                                                (addr, vout_id,mined_time)

                        db.session.execute(insert_ud_transaction_recods_address_sql)
                else :
                    print('nonstandard',TX_ID)
            except Exception as e:
                print("",e)
        #####vin
        vin = res['result']['vin']

        if len(vin[0]) > 2 :
            for index in range(len(vin)):
                vin_txid = vin[index]['txid']
                vout_index = vin[index]['vout']
                insert_ud_transaction_recods_vin_sql = "INSERT INTO ud_transaction_recods_vin(txid, vout , vin_txid , ud_transaction_recordsid,height) VALUES ('%s', '%s', '%s', '%s', '%s')" % \
                                                        (TX_ID, vout_index, vin_txid, ud_transaction_recordsid,HEIGHT)
                db.session.execute(insert_ud_transaction_recods_vin_sql)

        else :
            coinbase = vin[0]['coinbase']
            insert_ud_transaction_recods_vin_sql = "INSERT INTO ud_transaction_recods_vin(txid , coinbase , ud_transaction_recordsid,height) VALUES ('%s', '%s', '%s', '%s')" % \
                                                   (TX_ID, coinbase, ud_transaction_recordsid,HEIGHT)
            db.session.execute(insert_ud_transaction_recods_vin_sql)

def block_load(height):
    try:

        ub_block_query_sql = "select height from ud_block where height = %s" % \
                             (height)
        result = db.session.execute(ub_block_query_sql)
        block = result.fetchone()

        txList = []
        if block == None:


            payload = dumps({"method": 'getblockhash', "params": [height]})
            response = request("POST", url, data=payload, auth=auth)
            res = loads(response.text)
            blockHash =  res['result']

            #
            payload = dumps({"method": 'getblock', "params": [blockHash]})
            response = request("POST", url, data=payload, auth=auth)
            res = loads(response.text)

            ####
            height = res['result']['height']
            size = res['result']['size']
            bits = res['result']['bits']
            difficulty = res['result']['difficulty']
            previous_block =res['result']['previousblockhash']
            next_block =res['result']['nextblockhash']
            timestamp =res['result']['time']
            transactions_number = len(res['result']['tx'])
            block_reward = 112.96602502
            if height > 57599:
                block_reward=165.377




            insert_sql = "INSERT INTO ud_block(height,mined_by,difficulty,transactions_number,timestamp,Size,Bits, Block_reward , Previous_Block , Next_Block , BlockHash) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                               (height, '', difficulty, transactions_number, timestamp, size, bits, block_reward,previous_block, next_block, blockHash)

            result = db.session.execute(insert_sql)
            ud_blockid = result.lastrowid

            for index in  range(len(res['result']['tx'])):
                txList.append(res['result']['tx'][index])
            save_transaction(txList,ud_blockid)

        else:
            print('已存在',height)

        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print str(e)
    finally:
        print('finally')

def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
    time_array = time.localtime(time_stamp)
    str_date = time.strftime(format_string, time_array)
    return str_date


def load_height():
    payload = dumps({"method": 'getblockcount', "params": []})
    response = request("POST", url, data=payload, auth=auth)
    res = loads(response.text)
    endHeight = res['result']
    return endHeight

<file_sep>/**
 * Created by admin on 2017/4/14.
 */

 import axios from 'axios';

const baseURL = 'http://172.16.31.10:5000/';
const headers = {
	'Content-Type': 'application/json',
	'Access-Control-Allow-Methods': 'GET, POST, PUT',
	'Access-Control-Allow-Origin': '*',
	'Access-Control-Allow-Headers': 'X-Requested-With'
};

const http = axios.create({
  // baseURL,
  // timeout: 1000,
  // headers
});



export const get = function (url, params) {
	// let URL = baseUrl + url;
	// console.log('URL:', URL)
	// return Promise.resolve(function () {
		return http.get(url, {params})
	// }())
};

export const post = (url, params) => {
	// return Promise.resolve(function () {
		return http.post(url, params)
	// }())
};<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestPriceTrend} from 'actions/pricetrend';


class PriceTrend extends Component {
  constructor(props) {
    super(props);
    this.state = {
      period: 'day',
      format: '{value: %H:%M}',
      tickInterval: 3600 * 1000

    }
    this.renderTrend = this.renderTrend.bind(this);
    this.changePeriod = this.changePeriod.bind(this);
  }

  render() {
    let {period} = this.state;
    return (
      <div>

        <p className='change-period-tab'>
          <span className={`${period === 'day'? 'active': '' }`} onClick={() => this.changePeriod('day')}>一天</span>
          <span className={`${period === 'week'? 'active': '' }`} onClick={() => this.changePeriod('week')}>一周</span>
        </p>
        
        <div id='price-trend-container'></div>

      </div>
    )
  }

  changePeriod(period) {
    let {getPriceTrend} = this.props;
    this.setState({period})
    if(period === 'day') {
      this.setState({
        format: '{value: %H:%M}',
        tickInterval: 3600 * 1000
      })
      getPriceTrend(period)

    } else if(period === 'week') {
      this.setState({
        format: '{value: %m-%d}',
        tickInterval: 24 * 3600 * 1000
      })
      getPriceTrend(period)

    }
  }

  componentWillReceiveProps(props) {
    let data = props.data, total = [];
    data.length > 0 && data.map((item, idx) => {
      let time = item[0] + (8 * 60 * 60 * 1000);
      item[0] = time;
    })
    this.setState({data}, this.renderTrend)
  }

  componentDidMount() {
    this.renderTrend();
  }

  renderTrend() {
    let {format, tickInterval} = this.state;
    let {data} = this.state;
    // let formats='%m-%d';
    Highcharts.chart('price-trend-container', {
      chart: {
        zoomType: 'x'
      },
      title: {
        text: '',
      },
      subtitle: {
        text: ''
      },
      xAxis: {
        type: 'datetime',
        labels: {
          format: format
        },
        tickInterval: tickInterval,
        // startOnTick: true,
        // endOnTick: true,
        showLastLabel: true,
      },
      yAxis: {
        title: {
          text: ''
        },
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true,
        tickPositions: [0, 1, 2, 3, 4, 5, 6]
      },
      legend: {
        enabled: false
      },
      plotOptions: {
        area: {
          fillColor: {
            linearGradient: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: 1
            },
            stops: [
              [0, Highcharts.getOptions().colors[0]],
              [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
            ]
          },
          marker: {
            radius: 2
          },
          lineWidth: 1,
          states: {
            hover: {
              lineWidth: 1
            }
          },
          threshold: null
        }
      },

      series: [{
        type: 'area',
        name: 'price',
        data: data,
      }]
    });
    
  }
}

function mapState(state) {
  return {
    data: state.priceTrend.list
  }
}

function mapDispatch(dispatch) {
	return {
		getPriceTrend: (period) => dispatch(requestPriceTrend(period)),
  }
}

export default connect(mapState, mapDispatch)(PriceTrend);<file_sep>
const initState = {isFetching: true, fetched: false, transList: [],};

export default function transListReducer(state = initState, action) {
	switch (action.type) {
		case 'fetchTransList' :
			return Object.assign({}, state, {isFetching: true, fetched: false});
		case 'reciveTransList':
			return Object.assign({}, state, {isFetching: false, fetched: true, transList: action.transList});
		case 'fetchTransListrErr':
			return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
		default :
			return state;
	}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *
import traceback

###账户数量统计


def trans_address_count(curr_time):
  try:

      address_query_sql = "";
      if curr_time == '':
         address_query_sql = "select (select count(distinct address) from ud_address_details where `Final_Balance`>=10000) as gt10000,(select count(distinct address) from ud_address_details where `Final_Balance`>0) as gt0,(select count(distinct address) from ud_address_details) as address_num"
         curr_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
      else:
        address_query_sql = "select  count(CASE WHEN a.`Final_Balance`>=10000 THEN 1 end) as gt10000,count(CASE WHEN a.`Final_Balance`>0 THEN 1 end) as gt0,count(distinct a.address)  as address_num from (select address,   sum(CASE WHEN has_vin=0 THEN value end) as Final_Balance from ud_transaction_recods_vout  vout  where vout.`mined_day`<=DATE_FORMAT('%s','%%Y-%%m-%%d') group by address) a" % \
                          (curr_time)
      print address_query_sql
      res = db.session.execute(address_query_sql)
      address_count = res.fetchone()

      gt10000_address = address_count[0]
      gt0_address = address_count[1]
      address_num = address_count[2]

      trans_address_query_sql = "select count(distinct address) from ud_transaction_recods_vout where mined_time>=DATE_ADD('%s',INTERVAL -7 DAY) and mined_time<DATE_ADD('%s',INTERVAL 0 DAY) and has_vin =1" % \
                                (curr_time,curr_time)
      res = db.session.execute(trans_address_query_sql)
      trans_address_num = res.fetchone()
      trans_num = trans_address_num[0]


      trans_address_query = "select * FROM ud_trans_address where create_date=DATE_FORMAT('%s','%%Y-%%m-%%d') " % \
                            (curr_time)
      res = db.session.execute(trans_address_query)
      trans_address = res.fetchone()
      if trans_address == None:
          trans_address_insert_sql = "insert into ud_trans_address(create_date , gt10000_address, gt0_address, trans_num, address_num ) VALUES(DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s','%s','%s','%s')" % \
                                     (curr_time, gt10000_address, gt0_address, trans_num,address_num)
          db.session.execute(trans_address_insert_sql)
      else :
          trans_address_update_sql = "update ud_trans_address set gt10000_address='%s', gt0_address='%s', trans_num='%s', address_num='%s'  where create_date=DATE_FORMAT('%s','%%Y-%%m-%%d')" % \
                                     (gt10000_address, gt0_address, trans_num, address_num,curr_time)
          db.session.execute(trans_address_update_sql)

      db.session.commit()
  except Exception as e:
      db.session.rollback()
      traceback.print_exc()




def tran_address_job(update_time):
    #update_time = datetime.datetime.now().strftime('%Y-%m-%d')
    trans_address_count(update_time)



<file_sep>/**
 * Created by admin on 2017/3/3.
 */
import React, {Component} from 'react'
import {connect} from 'react-redux';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import MyTabContainer from 'components/myTabContainer';

import {requestHomeOrder} from 'actions/homeActions';
import {requestAddressList} from 'actions/addressAction';
import {requestPriceTrend} from 'actions/pricetrend';
import {requestTransList} from 'actions/transAction';


class Home extends Component {
	constructor(props) {
		super(props);
		this.state = {
		};
	}

	componentDidMount() {
		let {getOrders, getAddressList, getPriceTrend, getTransData} = this.props;
		getOrders();
		getAddressList();
		getPriceTrend();
		getTransData();
	}

	render() {
		return (
	    <div className="home-container">
				<Navbar>
			    <Navbar.Header>
				    <Navbar.Brand>
					    <a href="#"><img src={require('assets/icons/logo.png')} /></a>
				    </Navbar.Brand>
				    <Navbar.Toggle />
			    </Navbar.Header>
			    <Navbar.Collapse>
				    <Nav>
					    <NavItem eventKey={1} href="http://explorer.ulord.one/">
						    Blocks
					    </NavItem>
					    <NavItem eventKey={2} href="http://ulord.one/">
						    Ulord
					    </NavItem>
					    <NavItem eventKey={3} href="#">
						    Monitor
					    </NavItem>

				    </Nav>
			    </Navbar.Collapse>
		    </Navbar>
		    
				
				<div className='main-container'>
					<MyTabContainer />
				</div>

	    </div>

    );
	}

	shouldComponentUpdate(nextProps, nextState) {
		return this.props.router.location.action === 'PUSH';   //防止页面二次渲染
	}
}


function mapStateToProps(state) {
	return {orders: state.homeOrder.orders}
}

function mapDispatchToProps(dispatch) {
	return {
		getOrders: () => dispatch(requestHomeOrder()),
		getAddressList: () => dispatch(requestAddressList()),
		getPriceTrend: () => dispatch(requestPriceTrend('day')),
		getTransData: () => dispatch(requestTransList()),

	}
}

export default connect(mapStateToProps, mapDispatchToProps)(Home)<file_sep>/**
 * Created by admin on 2017/3/3.
 */

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Provider } from'react-redux';
import { createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';

import AppRoute from './routes.js';
import reducers from 'reducers/index.js';
import './assets/style.scss';

const store = createStore(reducers,applyMiddleware(thunkMiddleware));



function App() {
    return(
        <Provider store={store}>
            {AppRoute}
        </Provider>
    )
}

ReactDOM.render(<App/>,document.getElementById('app'));<file_sep>from flask import Flask
from create_db import *

def trans_speed(f):
    trans_query = ""
    if f=="hour":
        trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d')  group by FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') ) a"
    elif f=="day":
        trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -30 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d')  group by FROM_UNIXTIME(timestamp,'%Y-%m-%d') ) a"
    elif f=="week":
        trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed,FROM_UNIXTIME(a.timestamp,'%W') w from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d')  group by FROM_UNIXTIME(timestamp,'%Y-%m-%d') ) a "
    elif f=="month":
        trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -12 month),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d')  group by FROM_UNIXTIME(timestamp,'%Y-%m') ) a"

    row_list = []
    try :

        res = db.session.execute( trans_query)
        row_list = res.fetchall()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print e

    trans_list = []
    for index in range(len(row_list)):
        list = []
        if f=="week":
            list.append(row_list[index][7])
        else:
            list.append(row_list[index][0])
        list.append(str(row_list[index][1]))
        list.append(str(row_list[index][2]))
        list.append(str(row_list[index][3]))
        list.append(str(row_list[index][4]))
        list.append(str(row_list[index][5]))
        list.append(str(row_list[index][6]))
        trans_list.append(list)


    return trans_list<file_sep>import React, { Component } from 'react';
import {Table} from 'react-bootstrap';
import { connect } from 'react-redux';


class MonitorTable extends Component {
  constructor(props) {
    super(props);
    this.renderTable = this.renderTable.bind(this);
    this._onClick = this._onClick.bind(this);
  }

  render() {
    return(
      <div className='monitor-table-container bg-white'>
        <Table responsive>
         {/* <thead> */}
            
          {/* </thead> */}
          <tbody className='monitor-table-body'>
          <tr className='table-header'>     
              <th>交易对</th>
              <th>UT</th>
            </tr>
          { this.renderTable()}
          </tbody>
        </Table>
        </div>
      
    )
  }

  renderTable(){
    let {data} = this.props;
    return data.length > 0 && data.map( (item, idx) => {
      return (
        <tr key={idx}>
            <td className='table-left-td'>
              <p>{item[3]==1? <span className='moni-label'>入</span> : <span className='red moni-label'>出</span>} <span>{item[2]}</span></p>
              <p style={{cursor:'pointer'}} onClick={() => this._onClick(item[0])}>{item[0]}</p>
            </td>
            <td className='num'>{item[1]}</td>
        </tr>
      )
    })
  }

  _onClick(hash) {
    location.href = `http://explorer.ulord.one/address/${hash}`;
  }
}



function mapState(state) {
  return {
    data: state.homeOrder.orders
  }
}


export default connect(mapState, null)(MonitorTable);
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import          #如果没有这一行，下一行可能会出错


SQLALCHEMY_DATABASE_URI='mysql://ulord:===password==@localhost:3306/tn?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS=True
SQLALCHEMY_POOL_SIZE=1000

ULORD_IP='http://127.0.0.1:9889/'
ULORD_USER ='ulordpool'
ULORD_PASSWORD='<PASSWORD>'<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import {Navbar, Nav, NavItem, Table} from 'react-bootstrap'


class Management extends Component {
	constructor(props) {
		super(props)
		this.state = {}
	}

  render() {
    return (
	    <div className="home-container">
		    <Navbar collapseOnSelect>
			    <Navbar.Header>
				    <Navbar.Brand>
					    <a href="#/"><img src={require('assets/icons/logo.png')} /></a>
				    </Navbar.Brand>
				    <Navbar.Toggle />
			    </Navbar.Header>
			    <Navbar.Collapse>
				    <Nav>
					    <NavItem eventKey={1} href="#">
						    用户数据管理
					    </NavItem>
					    {/* <NavItem eventKey={2} href="#">
						    Ulord
					    </NavItem>
					    <NavItem eventKey={2} href="#">
						    趋势
					    </NavItem> */}

				    </Nav>
			    </Navbar.Collapse>
		    </Navbar>

				<div className='main-container'>
					<div className='txt-title'>用户数据管理</div>
					<Table responsive bordered>
						<thead>
							<tr>
								
								<th>交易对</th>
								<th>UT</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								
								<td>卖出</td>
								<td>5000</td>
							</tr>
							<tr>
							
								<td>买入</td>
								<td>2000</td>
							</tr>
						</tbody>
					</Table>

				</div>




	    </div>

    );
  }
}

function mapState(state) {
  return {}
}

export default connect(mapState, null)(Management);
