【发布时间】: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