Home Forums Chart Support Need help for updating the data with flask Reply To: Need help for updating the data with flask

#36966

@james007,

In the code shared above, data is not getting updated as the template are rendered once with the data being sent and you are updating the chart dataPoint with same value on each interval. In order to update the data from database, you can create a route let say /get_cart_rate which will serve the data from the database on request. Then, you can use fetch request to retrieve the value and update the dataPoints. Please take a look at the sample code below for the same

@app.route("/get_cart_rate")
def get_cart_rate():
  cur = db.get_db().execute("SELECT item_name, quantity FROM cart_service order by id")
  rv = cur.fetchall()
  cur.close()
  index = []
  data = {}
  for i in rv:
  index.append(i)

  for key, value in index:
  data[key] = data.get(key, 0) + value
  
  return jsonify(data)
.
.
template file:
function getData() {
  fetch("/get_cart_rate")
    .then(response => response.json())
    .then(data => {
    dps = [];
    for (var label in data) {
      if (data.hasOwnProperty(label)) {
        dps.push({ label: label, y: data[label] }) 
      }
    }
    chart.data[0].set("dataPoints", dps);

    setTimeout(getData, 4000);

  });

}
setTimeout(getData, 2000); 

Also, check out this sample project for complete working code.

Realtime CanvasJS Chart in flask

—-
Manoj Mohan
Team CanvasJS