使用ajax更新散景图

时间:2018-05-11 17:35:36

标签: javascript python ajax flask bokeh

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

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

enter image description here

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

@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,以便绘图与表格一起更新,但页面上的所有其他元素都不受影响? < / p>

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

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.pydata.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
    <link href="http://cdn.pydata.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.pydata.org/bokeh/release/bokeh-0.12.15.min.js"></script>
    <script src="http://cdn.pydata.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>

1 个答案:

答案 0 :(得分:2)

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

关键是创建一个额外的文件,这里update_content.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.pydata.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
    <link href="http://cdn.pydata.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.pydata.org/bokeh/release/bokeh-0.12.15.min.js"></script>
    <script src="http://cdn.pydata.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>

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