Home > front end >  How can I update an already rendered built finished Chart.js page Flask?
How can I update an already rendered built finished Chart.js page Flask?

Time:04-04

How can I update an already rendered built finished Chart.js page Flask? There is already ready Chart.js on the template page. The value data for which is taken from Flask. After what action on the page the values in the Flask code changed. How can I make it so that after a certain action in the route, Flask is additionally updated Chart.js?

I have been thinking for a long time how to make it so that it is updated Chart.js when I change the values in the Flask route ("/range") - I can transfer them (changed DataFrame values) to the database - but then I don't know how to update Chart.js.

it's html code

<div >
        <div >
            <input type="text" name="From" id="From"  placeholder="From Date"/>
        </div>
        <div >
            <input type="text" name="to" id="to"  placeholder="To Date"/>
        </div>
        <div >
            <input type="button" name="range" id="range" value="Range" />
        </div>
      </div>
      <div id="purchase_order"></div>
      <hr>
      <div  style="align-content: center">
{#        <div ></div>#}

            </div>
            <div  style="align-content: center">
                <div  id="table-wrapper" style="align-content: center">
                    <table>
                        <thead>
                            {% for col in column_names %}
                            <th>{{col}}</th>
                            {% endfor %}
                        </thead>
                        <tbody>
                            {% for row in row_data %}
                            <tr>
                                {% for cell in row %}
                                <td>{{ cell }}</td>
                                {% endfor %}
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
{#        <div ></div>#}
      </div>

      <div >
        <div >
        </div>
        <div >
            <div>
              <canvas id="myChart" width="800px" style="align-content: center"></canvas>
            </div>
        </div>
        <div >
        </div>
      </div>
      <br>
    </div>

It's script

</script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        $(document).ready(function (){
            $.datepicker.setDefaults({
                dateFormat: 'yy-mm-dd'
            });
            $(function (){
                $("#From").datepicker();
                $("#to").datepicker();
            });
            $('#range').click(function (){
                var From = $('#From').val();
                var to = $('#to').val();
                if (From != '' && to != '')
                {
                    $.ajax({
                        url:"/range",
                        method:"POST",
                        data:{From:From, to:to},
                        success:function (data)
                        {
                            $('#table-wrapper').html(data);
                            $('#table-wrapper').append(data.htmlresponse);
                        }
                    });
                }
                else
                {
                    alert("Please Select the Date")
                }
            });
        });
    </script>


    <script>
      const labels = [{% for item in os_x %}
      "{{ item }}",
          {% endfor %}];

      const data = {
        labels: labels,
        datasets: [{
          label: 'My First dataset',
          backgroundColor: 'rgb(255, 99, 132)',
          borderColor: 'rgb(255, 99, 132)',
          data: [{% for item in os_y %}
              {{ item }},
              {% endfor %}],
        }]
      };

      const config = {
        type: 'line',
        data: data,
        options: {}
      };
    </script>
    <script>
      const myChart = new Chart(
        document.getElementById('myChart'),
        config
      );
    </script>

it's Flask routes

@app.route('/', methods=['GET','POST'])
@app.route('/index')
def home_page():  # put application's code here
    df = pd.read_sql('select * from kotel', con=db.engine)
    df['date'] = df['date'].dt.round('2min')
    y_data = df['tnv'].tolist()
    x_data = df['date'].tolist()
    df_graph = df.copy()
    return render_template('index new.html', column_names=df.columns.values, row_data=list(df.values.tolist()), column_names_graph=df_graph.columns.values, os_y = y_data, os_x = x_data)


@app.route("/range", methods=["POST","GET"])
def range():
    if request.method == 'POST':
        From = request.form['From']
        to = request.form['to']
        df = pd.read_sql('select * from kotel', con=db.engine)
        df['date'] = pd.to_datetime(df['date'])
        df = df.loc[(df['date'] >= From) & (df['date'] <= to)]
        df['date'] = df['date'].dt.round('2min')
    return jsonify({'htmlresponse': render_template('response.html', column_names=df.columns.values, row_data=list(df.values.tolist()))})

CodePudding user response:

If the page is already loaded, only the values sent with the first request are displayed. If you want to see constantly updated values in your chart, you should use Websockets.

I've never worked with charts.js before, but I've used Flot Plot with Flask and Websocket to stream values to a chart in real time. it works great.

You can read more about Websockets and Flask here

If you want to load new values after and action, as example a click over a button, then you have to use ajax.

i found this page that could help you.

CodePudding user response:

I see you are already using ajax. I would recommend just wrapping your code in a SetInterval() which will execute the code over and over again in a specific interval, you could do it like this

<script>
        $(document).ready(function (){
          setInterval(function() {
            $.datepicker.setDefaults({
                dateFormat: 'yy-mm-dd'
            });
            $(function (){
                $("#From").datepicker();
                $("#to").datepicker();
            });
            $('#range').click(function (){
                var From = $('#From').val();
                var to = $('#to').val();
                if (From != '' && to != '')
                {
                    $.ajax({
                        url:"/range",
                        method:"POST",
                        data:{From:From, to:to},
                        success:function (data)
                        {
                            $('#table-wrapper').html(data);
                            $('#table-wrapper').append(data.htmlresponse);
                        }
                    });
                }
                else
                {
                    alert("Please Select the Date")
                }
            });
        },1000);
});
    </script>

you can change the number at the end, it specifies how long you want your interval to be in ms, so right now it's set to run every 1 second.

  • Related