使用ajax更新散景图

Cle*_*leb 5 javascript python ajax flask bokeh

我有一个类似的问题,因为这一个.我有一个包含多个元素的网站,例如表格和散景图,我想在用户提供特定输入后更新.虽然我可以为表格完成此操作,但我不知道如何更新散景图.

在下面的示例中,我使用一个最小示例,其中用户输入确定表的维度.所以输出看起来像这样:

在此输入图像描述

该表的更新效果很好并且符合预期,但是,我很难相应地更新绘图.我可以轻松地使用它进行初始化(整个代码可以在本文末尾找到):

@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)
Run Code Online (Sandbox Code Playgroud)

然后可以通过获取用户的选择

@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)
Run Code Online (Sandbox Code Playgroud)

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

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

1)现在,绘图始终是从头开始绘制的,理想情况下,只会更新数据.

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

如果没有其他答案显示,我非常乐意为@Anthonydouc提供积分,因为他的答案很好.

这是我的整个代码:

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)
Run Code Online (Sandbox Code Playgroud)

和我的 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>
Run Code Online (Sandbox Code Playgroud)

Ant*_*ouc 5

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

现在有三个文件 - 服务器代码(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)
Run Code Online (Sandbox Code Playgroud)

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 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>
Run Code Online (Sandbox Code Playgroud)

update_content.html

{{div_bok|safe}}
{{script_bok|safe}}
Run Code Online (Sandbox Code Playgroud)