我希望这种情况发生:用户从一个表单下拉列表中进行选择,该表单将变量传递给Flask服务器的app_route函数,该函数调用一个由输入的那些参数动态过滤的sql,并将数据表返回给浏览器。
在Flask中,我设置了一个app_route,它为json文件提供url_。返回的对象是json dict,它是根据用户提交的表单中的参数过滤的sql查询的结果。表单的action函数将发布到此函数并返回json dict url。
Datatable需要数据的URL。它似乎不允许我使用Jinja模板变量。我的冲突是,我既需要重定向/呈现具有数据表的html页面的模板,又需要返回包含子字典的url。
我想render_template('the_page_with_datatable.html',my_local_json_dict_variable)。
我可以从表单提交的app_route下调用的函数中的render_template('the_page_with_datatable.html')或return(my_local_json_dict_variable)提交并分配给url_for位置,但不能同时指定两者。
怎么做?
因此,我已经可以使用常规的jinja变量返回数据frame_to_html,但我特别希望具有数据表功能。我不想呈现任何其他类型的表。我也可以使用静态sql呈现数据表,其中我已经使用了对api的sql响应。问题是submit form操作返回一个URL,当我需要两个URL时,返回json url和render_template url。
HTML / JS
<form class="form-inline" id="my_form" action="get_data" method="POST">
<div class="form-group">
<select name="year" class="selectpicker form-control">
{% for yr in years %}
<option value="{{ yr }}">{{ yr }}</option>
{% endfor %}
</select>
<select name="month" class="selectpicker form-control">
{% for month in months %}
<option value="{{ month }}">{{ month }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-default">Go</button>
</form>
<table id="values_table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Date</th>
<th>values_€</th>
</tr>
</thead>
</table>
<script>
function setupData() {
$(document).ready(function () {
$('#values_table').DataTable( {
dom: 'Bfrtip',
"ajax": {
"url": "/get_data",
"dataType": "json",
"dataSrc": "data",
"contentType":"application/json"
},
"columns": [
{"data": "PersonName"},
{"data": "PersonNumber"},
{"data": "Date"},
{"data": "values_€"},
]
});
});
});
}
$( window ).on( "load", setupData );
</script>
Flask routes
#renders page with select form and datatable
@app.route("/values_select" , methods=['GET','POST'])
def values_select():
years, months = api().values_select()
return render_template('values_select.html', years=years, months=months)
#get json data for datatable to parse from url
@app.route("/get_data" , methods=['GET','POST'])
def get_data():
year = request.form.get('year')
month = request.form.get('month')
data = assets_api().values(month, year)
return jsonify(data=data)
最好有第二条返回json的路由,并利用数据表的ajax数据源。基本概述:
您的json路由(作为请求arg下拉列表):
@app.route('/get_data')
def get_json():
filter_val = request.args.get('filter')
result = # Your query here (using filter_val, or all rows if none?)
return jsonify(result)
您当前的路线可能会保持不变,但是:
def my_page():
# ...
return render_template('page.html')
和js:
$('#table').DataTable( {
ajax: {
url: "{{ url_for('get_json') }}?filter=" + $("#dropdown").val(),
dataSrc: ''
},
columns: [ ... ]
} );
在datatables ajax指南中对此进行了更多(更好)的解释。但我希望这是一个开始。
编辑:
一种是设置,您可以稍微不同地处理数据的重新获取。您不再需要该表格。您可以单击按钮,或更改下拉菜单(如下)。调用该table.reload()
函数将重新获取数据。就像是:
$("#the_dropdown").change(function() {
table.reload();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句