如何更新已经渲染的已建成的成品图表。

发布于 2025-01-18 21:59:27 字数 5409 浏览 0 评论 0原文

如何更新已经渲染完成的 Chart.js 页面 Flask? 模板页面上已经有准备好的Chart.js。 其值数据取自 Flask。 在页面上执行什么操作后,Flask 代码中的值发生了变化。 我怎样才能在路线中执行某个操作后,Flask 会另外更新 Chart.js?

我已经思考了很长一段时间如何制作它,以便当我更改 Flask 路径(“/range”)中的值时更新 Chart.js - 我可以将它们(更改的 DataFrame 值)传输到数据库 - 但是然后我不知道如何更新Chart.js。

这是 html 代码

<div class="row">
        <div class="col-md-3">
            <input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
        </div>
        <div class="col-md-3">
            <input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
        </div>
        <div class="col-md-6">
            <input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
        </div>
      </div>
      <div id="purchase_order"></div>
      <hr>
      <div class="row" style="align-content: center">
{#        <div class="col col-lg-0"></div>#}

            </div>
            <div class="outer-wrapper" style="align-content: center">
                <div class="table-wrapper" 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 class="col col-lg-0"></div>#}
      </div>

      <div class="row">
        <div class="col-md-1">
        </div>
        <div class="col-md-10">
            <div>
              <canvas id="myChart" width="800px" style="align-content: center"></canvas>
            </div>
        </div>
        <div class="col-md-1">
        </div>
      </div>
      <br>
    </div>

这是脚本

</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>

这是 Flask 路由

@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()))})

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 class="row">
        <div class="col-md-3">
            <input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
        </div>
        <div class="col-md-3">
            <input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
        </div>
        <div class="col-md-6">
            <input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
        </div>
      </div>
      <div id="purchase_order"></div>
      <hr>
      <div class="row" style="align-content: center">
{#        <div class="col col-lg-0"></div>#}

            </div>
            <div class="outer-wrapper" style="align-content: center">
                <div class="table-wrapper" 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 class="col col-lg-0"></div>#}
      </div>

      <div class="row">
        <div class="col-md-1">
        </div>
        <div class="col-md-10">
            <div>
              <canvas id="myChart" width="800px" style="align-content: center"></canvas>
            </div>
        </div>
        <div class="col-md-1">
        </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()))})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘴硬脾气大 2025-01-25 21:59:27

如果页面已经加载,则仅显示带有第一个请求的值。如果您想在图表中查看不断更新的值,则应使用Websocket。

我以前从未使用过Charts.js,但是我使用了带有烧瓶和Websocket的Flot图将其实时流式传输到图表。它效果很好。

您可以阅读有关Webockets的更多信息和烧瓶在这里 此后的新值和操作,例如单击按钮,然后您必须使用Ajax。

我发现此页面可以帮助您。

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.

淡莣 2025-01-25 21:59:27

我看到你已经在使用ajax了。我建议将您的代码包装在 SetInterval() 中,它将在特定的时间间隔内一遍又一遍地执行代码,您可以这样做,

<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>

您可以更改最后的数字,它指定您希望时间间隔以毫秒为单位,因此现在设置为每 1 秒运行一次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文