在一定时间间隔(10 sec)之后从不断增加的数据库(如mysql)中获取数据,使用烧瓶



我想使用python和flask创建一个API,并从不断增加数据的数据库中以常规时间间隔(10 sec(获取数据,而我不想要数据。获取已经获取的旧数据。

说您当前有一个API端点,该端点返回所有数据库存储的数据:

@app.route('/data', methods=['post'])
def data():
    all_the_data = Data.query.order_by(Data.created.desc()).all()
    return jsonify(results=all_the_data)

所以您的ajax呼叫当前正在做类似:

$.ajax({
    type: "POST",
    url: "/data",
    dataType: "json",
    success: function(data) { 
        console.log(data);
        update_graph(data);
    }
});

您只需要一种方法来使系统过滤出去的事情,然后回到客户端 - 因此,我们不必查询所有数据,而是可以根据参考来过滤:

@app.route('/data', methods=['post'])
def data():
    client_data = request.json
    reference = client_data.get('reference')
    if reference:
        # we have a reference, so lets filter the query:
        query_data = Data.query.filter(Data.id>reference).order_by(Data.created.desc()).all()
    else:
        # no reference, so send the lot!
        query_data = Data.query.order_by(Data.created.desc()).all()
    return jsonify(results=query_data)

然后,您的Ajax请求需要从其最后一个查询中获取最后一个参考 - 并将其提供给API端点:

$.ajax({
    type: "POST",
    url: "/data",
    data: JSON.stringify({ reference: 999 }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
       console.log(data)
       update_graph(data["results"]);
    }
});

因此,您只需要从您收到的最后一组值中找到如何获得reference值(API可以将其发送回另一个密钥,或者您可以在JavaScript中进行轮询当前集,等等(。

最新更新