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

Flask+SQLite3应用中HTML页面重复显示用户数据问题

问题:Flask页面重复显示同一用户数据

尝试用Flask、Python和SQLite3制作HTML表格展示数据库中所有用户,但页面重复显示同一个用户。

Python后端代码

@app.route('/admin')
def admin():
    db = sqlite3.connect("users.db", check_same_thread=False)
    c = db.cursor()
    if 'token' in session:
        try:
            token = session['token']
            c.execute("SELECT admin FROM users WHERE token=?", (token,))
            result = c.fetchone()
            if result[0] == "yes":
                # Fetch all the users from the database
                c.execute("SELECT * FROM users")
                users = c.fetchall()
                print(users)
                db.commit()
                db.close()
                return render_template("foradmins.html", users=users)
        except TypeError as e:
                print(e)
                return render_template("foradmins.html",users=[])
    else:
        return redirect(url_for('login'))

HTML模板代码

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Password</th>
            <th>Token</th>
            <th>admin?</th>
            <th>Ban</th>
        </tr>
    </thead>
    <tbody>
        {% for user in users %}
        <tr>
            <td>{{ user[0] }}</td>
            <td>{{ user[1] }}</td>
            <td>{{ user[2] }}</td>
            <td>{{ user[3] }}</td>
            <td>{{ user[4] }}</td>
            {% if isadmin=='yes' %}
            <td>{{ isadmin }}</td>
            {% elseif isadmin=='no'%}
            <td>{{ isadmin }} <button onclick="addadmin('{{ user[4] }}')">Add admin</button></td>
            {% endif %}    
            <td><button onclick="banUser('{{ user[4] }}')">Ban</button></td>
        </tr>
        {% endfor %}
    </tbody>
</table>

问题排查与解决方案

  1. 先确认查询结果是否正确
    查看Python控制台的print(users)输出:

    • 如果输出的是多条重复的用户数据,说明数据库中本身存在重复数据,或是查询逻辑有问题(当前SELECT * FROM users语句无语法错误,优先检查数据库数据)。
    • 如果输出的是正常的多条不同用户数据,问题出在HTML模板。
  2. 修正模板变量引用错误
    模板中错误使用了未定义的全局变量isadmin,导致所有行显示同一状态,甚至可能引发渲染异常。需要替换为当前循环用户的admin字段:
    假设users表字段顺序为id, username, email, password, token, admin,修改模板中的admin判断部分:

    {% if user[5] == 'yes' %}
    <td>{{ user[5] }}</td>
    {% elseif user[5] == 'no'%}
    <td>{{ user[5] }} <button onclick="addadmin('{{ user[4] }}')">Add admin</button></td>
    {% endif %}
    
  3. 优化后端代码细节
    移除多余的db.commit()——查询操作不需要提交事务;同时建议规范数据库连接管理,避免check_same_thread=False带来的线程安全问题(可改用Flask-SQLAlchemy或请求钩子自动关闭连接)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:42:40