You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask中通过GET方法获取表格行数据或ID?

解决方案:Flask中通过GET传递pandas表格行数据/ID

问题根源

出现IP/%7B%7B是因为pandas的to_html()生成的是纯静态HTML,会把你写的Jinja2模板语法(比如{{ row.id }})当成普通字符串输出,浏览器自动将{{ }}转义为URL编码%7B%7B,导致模板语法未被Flask渲染。


方案1:手动生成带点击事件的表格(直接处理)

跳过to_html()的静态限制,手动拼接HTML行并绑定点击事件,实现GET传参:

from flask import Flask, request
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    # 构造示例数据,确保包含唯一ID列
    df = pd.DataFrame({
        'id': [1,2,3],
        'name': ['Alice', 'Bob', 'Charlie'],
        'age': [25,30,35]
    })

    # 手动生成带点击事件的表格
    table_html = '<table border="1">'
    # 渲染表头
    table_html += '<tr>' + ''.join([f'<th>{col}</th>' for col in df.columns]) + '</tr>'
    # 渲染表体,每行绑定点击事件
    for _, row in df.iterrows():
        row_id = row['id']
        # 拼接onclick事件,传递ID到JS函数
        table_html += f'<tr onclick="handleRowClick({row_id})">'
        table_html += ''.join([f'<td>{val}</td>' for val in row.values])
        table_html += '</tr>'
    table_html += '</table>'

    # 嵌入处理GET请求的JS
    page_html = f'''
    <html>
        <body>
            {table_html}
            <script>
                function handleRowClick(id) {{
                    // 选项1:发送GET请求到后端接口
                    fetch(`/process?id=${{id}}`)
                        .then(res => res.text())
                        .then(msg => console.log(msg));
                    
                    // 选项2:跳转至详情页并携带ID
                    // window.location.href = `/detail?id=${{id}}`;
                }}
            </script>
        </body>
    </html>
    '''
    return page_html

@app.route('/process')
def process_row():
    row_id = request.args.get('id')
    # 此处可根据ID查询完整行数据并处理
    return f"已接收行ID:{row_id}"

@app.route('/detail')
def detail_page():
    row_id = request.args.get('id')
    # 渲染详情页逻辑
    return f"详情页:行ID {row_id}"

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

方案2:用Jinja2模板渲染表格(推荐)

将DataFrame传入Jinja2模板,直接用模板语法生成带GET链接的行,彻底避免静态HTML的转义问题:

Flask路由代码

from flask import Flask, render_template, request
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    df = pd.DataFrame({
        'id': [1,2,3],
        'name': ['Alice', 'Bob', 'Charlie'],
        'age': [25,30,35]
    })
    return render_template('table.html', df=df)

@app.route('/detail')
def detail():
    row_id = request.args.get('id')
    # 根据ID获取完整行数据并渲染详情页
    return f"获取到的行ID:{row_id}"

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

模板文件templates/table.html

<html>
<body>
    <table border="1">
        <tr>
            {% for col in df.columns %}
                <th>{{ col }}</th>
            {% endfor %}
        </tr>
        {% for _, row in df.iterrows() %}
            <!-- 点击整行跳转,通过GET传递ID -->
            <tr onclick="window.location.href='/detail?id={{ row.id }}'">
                {% for val in row.values %}
                    <td>{{ val }}</td>
                {% endfor %}
            </tr>
        {% endfor %}
    </table>
</body>
</html>

特殊场景处理:必须用to_html()时

如果一定要保留to_html()的输出,可以通过正则替换给行添加属性和事件:

table_html = df.to_html()
# 给每行添加data-id属性和点击事件
import re
table_html = re.sub(r'<tr>', r'<tr onclick="handleRowClick(this.getAttribute(\'data-id\'))"', table_html)
# 替换ID列的<td>标签,添加data-id属性到对应行
table_html = re.sub(r'<td>(\d+)</td>', r'<td data-id="\1">\1</td>', table_html)

内容的提问来源于stack exchange,提问作者OttoLuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:23:01