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

Flask后端如何在函数间传递变量?词汇训练器开发问题

解决词汇训练器中难度更新的ID传递问题

首先明确:绝对不要用全局变量,Flask是多线程服务,全局变量会被并发请求覆盖,导致更新错误的词汇,完全不可行。正确的做法是让前端在调用更新难度的API时,把词汇ID一起传过来——毕竟前端在learn.html里已经拿到了完整的word对象,里面包含Nummer(也就是你要的word_id)。

具体修改步骤

1. 后端修正update_difficulty函数

原来的函数里word_id是未定义的,而且表名拼写前后不一致(Vokabelna和Vokabeln),同时建议用with语句自动管理数据库连接和游标,避免资源泄漏:

@app.route("/api/difficulty", methods=['POST'])
def update_difficulty():
    # 接收前端传来的JSON数据,包含新难度和词汇ID
    data = request.get_json()
    new_difficulty = data.get('new_difficulty')
    word_id = data.get('word_id')

    # 校验必填参数
    if not new_difficulty or not word_id:
        return jsonify({'error': '缺少必要参数'}), 400

    try:
        # 使用with语句自动关闭连接和游标
        with connect_db() as con:
            with con.cursor() as cursor:
                # 注意统一表名,这里改成你实际的表名(之前的Vokabelna/Vokabeln要一致)
                cursor.execute(
                    "UPDATE Vokabeln SET schwierigkeit = %s WHERE Nummer = %s",
                    (new_difficulty, word_id)
                )
                con.commit()
        return jsonify({'message': '难度更新成功!'})
    except Exception as e:
        # 出错时回滚事务
        con.rollback()
        return jsonify({'error': str(e)}), 500

2. 前端在模板中添加难度按钮并传递ID

在learn.html里,利用模板变量word.Nummer获取词汇ID,给每个难度按钮绑定点击事件,点击时把ID和新难度一起发给后端API:

<!-- 假设模板中显示难度按钮的部分 -->
{% if show_difficulty_buttons %}
<div class="difficulty-buttons">
    <button class="diff-btn" data-word-id="{{ word.Nummer }}" data-difficulty="1">简单</button>
    <button class="diff-btn" data-word-id="{{ word.Nummer }}" data-difficulty="2">中等</button>
    <button class="diff-btn" data-word-id="{{ word.Nummer }}" data-difficulty="3">困难</button>
</div>
{% endif %}

<script>
// 给所有难度按钮绑定点击事件
document.querySelectorAll('.diff-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
        const wordId = btn.dataset.wordId;
        const newDifficulty = btn.dataset.difficulty;
        
        try {
            const response = await fetch('/api/difficulty', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    word_id: wordId,
                    new_difficulty: newDifficulty
                })
            });
            
            const result = await response.json();
            // 可以把反馈显示在页面上,而不是alert
            alert(result.message);
        } catch (error) {
            console.error('更新难度失败:', error);
            alert('更新难度时出现错误');
        }
    });
});
</script>

额外注意点

  • 数据库表名要统一:你之前的lernen函数里查的是Vokabelna,但update_difficulty里更的是Vokabeln,这明显是拼写错误,必须改成一致的表名,否则会找不到表或者更新错误的表。
  • 参数校验:后端一定要校验前端传来的参数是否存在,避免因为参数缺失导致SQL执行错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:23:19