I use flask to show a table and a graph. When I edit a cell, I trigger an API call ('/api/data'). This API call shall update the graph and remain everything else untouched. This means I do not want to use render_template, as this affects everything. I basically want to send new values to the graph. How does this work?
python:
from flask import Flask
from flask import Blueprint, redirect, render_template, url_for, request
from flask_login import current_user, login_required, logout_user
import pandas as pd
import json
import plotly
import plotly.express as px
app = Flask(__name__)
@app.route('/')
def index():
df = pd.DataFrame({
'a': ["a","b"],
'b': ["1","2"],
})
fig = px.scatter(df, x='a', y='b')
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
data = [{"datum": "1.6.22", "betreff": "neu1", "wert": "123"},
{"datum": "1.6.22", "betreff": "neu2", "wert": "123"},
{"datum": "1.6.22", "betreff": "neu3", "wert": "123"},
{"datum": "1.6.22", "betreff": "neu4", "wert": "123"},
{"datum": "1.6.22", "betreff": "neu5", "wert": "123"}]
return render_template('index3.jinja2', data=data, graphJSON=graphJSON)
@app.route('/api/data', methods=['GET', 'POST'])
def data():
print("/api/data")
try:
r = request.json
k = list(r.keys())
print(k)
print(r[k[0]] + " : " + r[k[0]])
except:
print("Nichts angepasst")
return {'data': [{"datum": "1.6.22", "betreff": "neu1", "wert": "123"},
{"datum": "1.6.22", "betreff": "neu2", "wert": "123"}]}
app.run(host='0.0.0.0', port=81, debug=True)
html:
<!doctype html>
<html>
<head>
<title>Basic Table</title>
<link href="https://unpkg.com/gridjs/dist/theme/mermaid.min.css" rel="stylesheet" />
<style>
body {
font-family: Sans-Serif;
}
</style>
</head>
<body>
<div>
<h1>Basic Table</h1>
<hr>
<div id="table"></div>
</div>
<div id='chart' class='chart'”></div>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script src="https://unpkg.com/gridjs/dist/gridjs.umd.js"></script>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
const editableCellAttributes = (data, row, col) => {
if (row) {
return {contentEditable: 'true', 'data-element-id': row.cells[0].data};
}
else {
return {};
}
};
new gridjs.Grid({
columns: [
{ id: 'datum', name: 'Datum' },
{ id: 'betreff', name: 'Betreff' },
{ id: 'wert', name: 'Wert', sort: false , 'attributes': editableCellAttributes},
],
data: [
{% for e in data %}
{
datum: '{{ e.datum }}',
betreff: '{{ e.betreff }}',
wert: '{{ e.wert }}'
},
{% endfor %}
],
}).render(document.getElementById('table'));
console.log("abcdefg")
const tableDiv = document.getElementById('table');
let savedValue;
tableDiv.addEventListener('focusin', ev => {
console.log("Start focusin: " + ev.target.tagName)
if (ev.target.tagName === 'TD') {
savedValue = ev.target.textContent;
}
console.log("End focusin: " + ev.target.tagName)
});
tableDiv.addEventListener('focusout', ev => {
console.log("Start focusout: " + ev.target.tagName)
if (ev.target.tagName === 'TD') {
if (savedValue !== ev.target.textContent) {
fetch('/api/data', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: ev.target.dataset.elementId,
[ev.target.dataset.columnId]: ev.target.textContent
}),
});
}
savedValue = undefined;
}
console.log("End focusout: " + savedValue)
});
var graphs = {{graphJSON | safe}};
Plotly.plot('chart',graphs,{});
</script>
</body>
</html>