是否可以使用 jQuery 使熊猫表可过滤/可搜索



>我正在使用 Flask 构建一个 Web 应用程序,但我目前在尝试创建一个带有搜索框的可过滤表(使用 pandas 构建)时陷入困境,您可以在其中搜索行中的项目,当找到该项目时,表格将折叠。就像这里的那个:https://www.w3schools.com/bootstrap/bootstrap_filters.asp

在上面的例子中,jQuery 过滤器函数应用于直接在 html 模板中创建的表,但我很难让它与熊猫数据帧一起使用(当我尝试通过搜索框搜索时没有任何反应)。

任何帮助将不胜感激:)

我 run.py 如下:

from flask import Flask, render_template
import pandas as pd
app = Flask(__name__)
@app.route("/")
def table():
    df = pd.read_csv("input.csv")
    return render_template("test.html", data=df.to_html(index=False))
if __name__ == '__main__':
    app.run(debug=True)

和我的测试 html 模板:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $({{data}}).filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>
</head>
<body>
    <div class="container">
      <h2>Browse Phosphosites</h2>
      <br><br>
      <p>Search the table for selected phosphosites or associated genes, chromosome locations and sequences:</p>  
      <input id="myInput" type="text" placeholder="Search...">
      <br><br>
      {{data | safe }}
    </div>
</body>
</html>

这是一种方法的工作试验:

from flask import Flask, render_template_string, session, request
import pandas as pd
app = Flask(__name__)
template = """
<!doctype html>
<input type="text" value="" name="my_filter" id="my_filter">
<div id="results">{{ data|safe }}</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
   $('#my_filter').keyup(function() {
       if ($(this).val().length >= 1) {
           var requested_code = document.getElementById('my_filter').value;
           $.ajax({
               type: 'POST',
               data: JSON.stringify({
                   'requested_code': requested_code
               }),
               contentType: 'application/json; charset=utf-8',
               url: "{{ url_for('filter_html') }}",
               success: function(resp) {
                   $("#results").html(resp);
               }
           });
       }
});
</script>
</html>
"""
@app.route("/")
def table():
    df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
    session['df'] = df.values.tolist()
    return render_template_string(template, data=df.to_html(index=False))

@app.route('/filter', methods=['GET', 'POST'])
def filter_html():
    df = pd.DataFrame(session['df'], columns=['a', 'b'])
    df = df[df['a'] == int(request.json.get('requested_code'))]
    return df.to_html(index=False)

if __name__ == '__main__':
    app.secret_key = 'hello'
    app.run(debug=True)

实质上,将 JQuery 函数添加到查找keyup事件的input框中。但是,这些应该触发对 Flask 中的 URL 终结点的 AJAX 请求,然后可以更新"results"div。可能有更简洁的方法来序列化要存储在会话中的数据;这只是为了说明一种方法。

默认session在 Flask 中相当小。如果您尝试存储太大而无法容纳的对象,它不会出错,问题只是被静默忽略。您需要使用flask-session来存储 DF 数据;您目前正在将整个内容发送到浏览器,因此我认为它不是特别大。

对于不太熟悉 Flask 但使用 Pandas 的人:您可以运行此代码,然后在浏览器中导航到127.0.0.1:5000。数字 1、2 或 3 可以有效地输入到搜索框中与 df 交互,其他任何内容都会导致空 df。

最新更新