我想使用 python 和烧瓶创建一个 api,它以固定的时间间隔(10 秒)从不断增加的数据库中获取数据,其中数据不断传入和存储。我不想获取已经获取的旧数据。
假设您当前有一个 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 中轮询当前设置等)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句