【问题标题】:Update a bokeh plot using ajax使用 ajax 更新散景图
【发布时间】:2018-10-22 04:13:27
【问题描述】:

我有一个与this one 类似的问题。我有一个网站,其中包含多个元素,例如表格和散景图,一旦用户提供特定输入,我想更新它们。虽然我可以为表格完成此操作,但我不知道如何更新散景图。

在下面的示例中,我使用了一个最小示例,其中用户输入决定了表格的尺寸。所以输出看起来像这样:

表格的更新效果很好,正如预期的那样,但是,我很难相应地更新情节。我可以很容易地使用它来初始化它(整个代码可以在这篇文章的末尾找到):

@app.route('/')
def index():

    # just an initial figure
    p = figure(plot_width=150, plot_height=100)

    p.line([1, 2, 3], [1, 2, 3])
    # save(p, 'testing.html')

    script_bok, div_bok = components(p)
    return render_template('index.html', div_bok=div_bok, script_bok=script_bok)

然后可以通过

获取用户的选择
@app.route('/_get_table')
def get_table():

    nrow = request.args.get('nrow', type=int)
    ncol = request.args.get('ncol', type=int)

    # the table we want to display
    df = pd.DataFrame(np.random.randint(0, 10, size=(nrow, ncol)))

    # the updated/new plot
    p = figure(plot_width=150, plot_height=100)

    p.line(list(range(nrow)), list(range(nrow)))
    # save(p, 'testing.html')

    script_bok, div_bok = components(p)

    # how would I pass those now?

    return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
                   columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]],
                   div_bok=div_bok,
                   script_bok=script_bok)

问题是:我现在如何将新组件提供给index.html,以便绘图与表格一起更新,但页面上的所有其他元素都保持不变?

现在有两个答案可以解决这个问题。我仍然决定使用赏金来找到更好的答案。可以改进的地方:

1) 现在,绘图总是从头开始绘制,理想情况下,只有数据会被更新。

2) 有没有办法避免额外的模板(下面称为update_content.html)?

如果没有其他答案出现,我非常乐意为@Anthonydouc 提供his nice answer 的积分。

这是我的全部代码:

from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
from bokeh.plotting import figure, show, save
from bokeh.embed import components

# Initialize the Flask application
app = Flask(__name__)


@app.route('/')
def index():

    # just an initial figure
    p = figure(plot_width=150, plot_height=100)

    p.line([1, 2, 3], [1, 2, 3])
    # save(p, 'testing.html')

    script_bok, div_bok = components(p)
    return render_template('index.html', div_bok=div_bok, script_bok=script_bok)


@app.route('/_get_table')
def get_table():

    nrow = request.args.get('nrow', type=int)
    ncol = request.args.get('ncol', type=int)

    # the table we want to display
    df = pd.DataFrame(np.random.randint(0, 10, size=(nrow, ncol)))

    # the updated/new plot
    p = figure(plot_width=150, plot_height=100)

    p.line(list(range(nrow)), list(range(nrow)))
    # save(p, 'testing.html')

    script_bok, div_bok = components(p)

    # how would I pass those now?

    return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
                   columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]],
                   div_bok=div_bok,
                   script_bok=script_bok)



if __name__ == '__main__':

    app.run(debug=True, threaded=True)

还有我的index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
    <link href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <div class="container">
      <div class="header">
          <h3 class="text-muted">some stuff</h3>
        </div>

        <hr class="mb-4">
     <div class="row">
      <div class="col-md-8">
      <form id="input_data_form" class="needs-validation" novalidate>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="nrow">rows</label>
            <input type="number" class="form-control" id="nrow" min="0" step="1" placeholder="" value="2" required>
            <div class="invalid-feedback">
              please provide an integer
            </div>
          </div>
          <div class="col-md-6 mb-3">
            <label for="ncol">columns</label>
            <input type="number" class="form-control" id="ncol" min="0" step="1" placeholder="" value="2" required>
            <div class="invalid-feedback">
              please provide an integer
            </div>
          </div>
        </div>
        <div class="form-row text-center">
          <div class="col-12">
              <button id="calculate" type="submit" class="btn btn-primary">Calculate!</button>
          </div>
       </div>
      </form>
      </div>
        <div class="col-md-4">

          <div class="header">
            <h5 class="text-muted">Plot results</h5>
          </div>
          {{div_bok|safe}}
          {{script_bok|safe}}
        </div>
     </div>

      <hr class="mb-4">

      <table id="a_nice_table" class="table table-striped"></table>

    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.js"></script>
    <script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        var table = null;
        $('#input_data_form').submit(function (event) {
            event.preventDefault();
            if ($('#input_data_form')[0].checkValidity() === false) {
                event.stopPropagation();
                if (table !== null) {
                    table.destroy();
                    table = null;
                    $("#a_nice_table").empty();
                  }
            } else {
                $.getJSON('/_get_table', {
                    nrow: $("#nrow").val(),
                    ncol: $("#ncol").val()

                  }, function(data) {

                  //document.body.append($(data.script_bok)[0]);

                  //$("#bokeh_plot").html(data.div_bok);

                  if (table !== null) {
                    table.destroy();
                    table = null;
                    $("#a_nice_table").empty();
                  }
                  table = $("#a_nice_table").DataTable({
                    data: data.my_table,
                    columns: data.columns

                  });
                });
            return false;
            }
            $('#input_data_form').addClass('was-validated');
        });

      });
    </script>
  </body>

【问题讨论】:

    标签: javascript python ajax flask bokeh


    【解决方案1】:

    我已从您的示例中删除了表格,只专注于更新散景图。在此示例中需要注意的重要一点是,每次按下计算时都会重新创建绘图。

    现在有三个文件 - 服务器代码 (app.py)、基本模板 (index.html) 和仅渲染散景图的模板 (update_content.html)。两个模板都需要像往常一样位于模板文件夹中。

    “_get_table”端点现在返回包含散景图的渲染 html。单击计算按钮将触发回调,然后向此端点提交发布请求。 app.py:

    from flask import Flask, render_template, request, jsonify
    import pandas as pd
    import numpy as np
    import json
    from bokeh.plotting import figure, show, save
    from bokeh.embed import components
    
    # Initialize the Flask application
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
    
        # just an initial figure
        p = figure(plot_width=150, plot_height=100)
    
        p.line([1, 2, 3], [1, 2, 3])
        # save(p, 'testing.html')
    
        script_bok, div_bok = components(p)
        return render_template('index.html', div_bok=div_bok, script_bok=script_bok)
    
    
    @app.route('/_get_table', methods=['GET','POST'])
    def get_table():
    
        # extract nrow, ncol via ajax post - contained in request.form
        nrow = request.form.get('nrow', type=int)
        ncol = request.form.get('ncol', type=int)
    
        # the updated/new plot
        p = figure(plot_width=150, plot_height=100)
    
        p.line(list(range(nrow)), list(range(nrow)))
    
        script_bok, div_bok = components(p)
    
        #return rendered html to the browser
    
        return render_template('update_content.html', div_bok=div_bok, script_bok=script_bok)
    
    
    
    if __name__ == '__main__':
    
        app.run(debug=True, threaded=True)
    

    索引.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
        <link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
        <link href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.css" rel="stylesheet" type="text/css">
      </head>
      <body>
        <div class="container">
          <div class="header">
              <h3 class="text-muted">some stuff</h3>
            </div>
    
            <hr class="mb-4">
         <div class="row">
          <div class="col-md-8">
          <form id="input_data_form" class="needs-validation" novalidate>
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="nrow">rows</label>
                <input type="number" class="form-control" id="nrow" min="0" step="1" placeholder="" value="2" required>
                <div class="invalid-feedback">
                  please provide an integer
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="ncol">columns</label>
                <input type="number" class="form-control" id="ncol" min="0" step="1" placeholder="" value="2" required>
                <div class="invalid-feedback">
                  please provide an integer
                </div>
              </div>
            </div>
            <div class="form-row text-center">
              <div class="col-12">
                  <button id="calculate" type="submit" class="btn btn-primary">Calculate!</button>
              </div>
           </div>
          </form>
          </div>
            <div class="col-md-4">
              <div class="header">
                <h5 class="text-muted">Plot results</h5>
              </div>
              <div id="plot-content">
                {{div_bok|safe}}
                {{script_bok|safe}}
              </div>
            </div>
         </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
        <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.js"></script>
        <script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.js"></script>
        <script type="text/javascript">
          $(document).ready(function(){
            $('#calculate').on('click', function(e){
              // prevent page being reset, we are going to update only
              // one part of the page.
              e.preventDefault()
              $.ajax({
                url:'./_get_table',
                type:'post',
                data:{'nrow':$("#nrow").val(),
                      'ncol':$("#ncol").val()},
                success : function(data){
                  // server returns rendered "update_content.html"
                  // which is just pure html, use this to replace the existing
                  // html within the "plot content" div
                  $('#plot-content').html(data)
                }
              })
            });
          });
        </script>
      </body>
    

    update_content.html

    {{div_bok|safe}}
    {{script_bok|safe}}
    

    【讨论】:

    • 太棒了,就像宣传的那样(赞成)。那么问题仍然是如何同时更新表。可以在jsonify 中返回render_template 吗?会试试...
    【解决方案2】:

    @Anthonydouc's excellent answer 让我走上了正轨,所以所有的功劳都应该归功于他;这只是对如何同时更新表的扩展。

    关键是创建一个附加文件,这里是update_content.html,它将包含绘图所需的 HTML,每次用户提供一些输入时都应更新该 HTML。它仅包含:

    {{div_bok|safe}}
    {{script_bok|safe}}
    

    鉴于此,可以使用render_template 生成代表图形的HTML 字符串,并通过jsonify 传递它。因此,更新后的烧瓶脚本如下所示:

    from flask import Flask, render_template, request, jsonify
    import pandas as pd
    import numpy as np
    import json
    from bokeh.plotting import figure, show, save
    from bokeh.embed import components
    
    # Initialize the Flask application
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
    
        return render_template('index.html')
    
    
    @app.route('/_get_table')
    def get_table():
    
        nrow = request.args.get('nrow', type=int)
        ncol = request.args.get('ncol', type=int)
    
        # the table we want to display
        df = pd.DataFrame(np.random.randint(0, 10, size=(nrow, ncol)))
    
        # the updated/new plot
        p = figure(plot_width=150, plot_height=100)
    
        p.line(list(range(nrow + 1)), list(range(nrow + 1)))
        # save(p, 'testing.html')
    
        script_bok, div_bok = components(p)
    
        # pass the div and script to render_template    
        return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
                       columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]],
                       html_plot=render_template('update_content.html', div_bok=div_bok, script_bok=script_bok))
    
    
    if __name__ == '__main__':
    
        app.run(debug=True, threaded=True)
    

    index.html 文件看起来像这样(确保使用正确的bokeh 版本,这里是0.12.15):

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
        <link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
        <link href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.css" rel="stylesheet" type="text/css">
      </head>
      <body>
        <div class="container">
          <div class="header">
              <h3 class="text-muted">some stuff</h3>
            </div>
    
            <hr class="mb-4">
         <div class="row">
          <div class="col-md-8">
          <form id="input_data_form" class="needs-validation" novalidate>
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="nrow">rows</label>
                <input type="number" class="form-control" id="nrow" min="0" step="1" placeholder="" value="2" required>
                <div class="invalid-feedback">
                  please provide an integer
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="ncol">columns</label>
                <input type="number" class="form-control" id="ncol" min="0" step="1" placeholder="" value="2" required>
                <div class="invalid-feedback">
                  please provide an integer
                </div>
              </div>
            </div>
            <div class="form-row text-center">
              <div class="col-12">
                  <button id="calculate" type="submit" class="btn btn-primary">Calculate!</button>
              </div>
           </div>
          </form>
          </div>
            <div class="col-md-4">
    
              <div class="header">
                <h5 class="text-muted">Plot results</h5>
              </div>
              <div id="plot_content">
    
              </div>
            </div>
         </div>
    
          <hr class="mb-4">
    
          <table id="a_nice_table" class="table table-striped"></table>
    
        </div>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
        <script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.js"></script>
        <script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.js"></script>
        <script type="text/javascript">
          $(document).ready(function() {
            var table = null;
            $('#input_data_form').submit(function (event) {
                event.preventDefault();
                if ($('#input_data_form')[0].checkValidity() === false) {
                    event.stopPropagation();
                    if (table !== null) {
                        table.destroy();
                        table = null;
                        $("#a_nice_table").empty();
                      }
                } else {
                    $.getJSON('/_get_table', {
                        nrow: $("#nrow").val(),
                        ncol: $("#ncol").val()
    
                      }, function(data) {
    
                      $('#plot_content').html(data.html_plot);
    
                      if (table !== null) {
                        table.destroy();
                        table = null;
                        $("#a_nice_table").empty();
                      }
                      table = $("#a_nice_table").DataTable({
                        data: data.my_table,
                        columns: data.columns
    
                      });
                    });
                return false;
                }
                $('#input_data_form').addClass('was-validated');
            });
    
          });
        </script>
      </body>
    

    可能有更好的选择,其中情节实际上只是更新而不是像此解决方案中那样完全重绘,但现在可以完成工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多