我可视化实时图表,例如此处的示例:Highcharts。基本上,它是来自生成随机数据的PHP脚本live-server-data.php
的数据的Ajax请求:
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: '/',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
//---live-server-data.php
<?php
$x = time() * 1000;
$y = rand(0, 100);
$ret = array($x, $y);
echo json_encode($ret);
?>
如何在Flask中做类似的事情,即从Flask请求随机生成的数字?
from flask import Flask, render_template, request, jsonify
import random, datetime, json
import time
app = Flask(__name__)
@app.route('/')
def index():
x = int(round(time.time() * 1000))
y = random.randint(0, 100)
return json.dumps([x, y])
if __name__ == '__main__':
app.run(debug=True)
答案 0 :(得分:1)
在Flask中简单得多:
@app.route('/')
def index():
x = datetime.timestamp(datetime.now()) * 1000
y = random.randint(0, 100)
return json.dumps([x, y])
但请注意,您必须在顶部添加以下导入才能实现此目的:
import random, datetime, json
from datetime import datetime