[英]Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask
我想使用python和flask创建一个api,它以固定的时间间隔(10秒)从不断增长的数据库中连续提取和存储数据,而我不想获取已经获取的旧数据。
Say you currently have an API endpoint that returns all the database stored data: 假设您当前有一个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)
So your ajax call currently doing something like: 因此,您的ajax调用当前正在执行以下操作:
$.ajax({
type: "POST",
url: "/data",
dataType: "json",
success: function(data) {
console.log(data);
update_graph(data);
}
});
You just need a way for the system to filter what's going out, back to the client-- so we instead of querying all the data, we can filter based on a reference: 您只需要让系统过滤出发生情况的方法,然后返回给客户端即可-因此我们无需查询所有数据,而是可以基于引用进行过滤:
@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)
Then your ajax request needs to get the last reference from the last query it did-- and supply that to the API endpoint: 然后,您的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"]);
}
});
So you just need to work out how to get that reference
value from the last set of values you recieved (the API could send that back as another key, or you could poll your current set within javascript, etc). 因此,您只需要弄清楚如何从您收到的最后一组值中获取该reference
值(API可以将其作为另一个键发送回去,或者您可以在javascript中轮询当前的组,等等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.