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

Flask传字典至Jinja2报错:'results'变量未定义

问题分析与解决方案

错误根源

当用户通过GET请求访问/wordCount路由时,你的Flask视图函数仅返回render_template('word_count.html'),没有传递results变量。而模板中直接尝试遍历results.items(),Jinja2找不到该变量,因此抛出UndefinedError。只有POST请求时才会生成并传递results,但首次加载页面是GET请求,必然触发错误。

修复方案

方案1:GET请求时传入空字典

修改Flask视图函数,在所有请求场景下都传递results变量:

@app.route('/wordCount' , methods= ['GET', 'POST'])
def wordCount ():
    results = {}  # 初始化空字典,确保所有请求都传递该变量
    if request.method == 'POST':
        wordCount_text = request.form['wordCount_text']
        wordCount_split = wordCount_text.split(' ')
        
        uniqueWords = []
        for word in wordCount_split:
            if word != '' and word not in uniqueWords:
                uniqueWords.append(word)
                results[word] = ""
        
        for word in uniqueWords:
            count = 0
            for word_2 in wordCount_split:
                if word == word_2:
                    count += 1
            results[word] = str(count)
       
    return render_template('word_count.html', results=results)

方案2:模板中添加存在性判断

在模板里先检查results是否存在且非空,再执行循环逻辑:

<table id = "word_table">
    <tr>
        <th> Word: </th>
        <th> Count: </th>
    </tr>

{% if results %}
    {% for key, value in results.items() %}
        <tr> <td> {{ key }} </td> <td> {{ value }} </td></tr>
    {% endfor %}
{% endif %}
</table>

代码优化建议

你当前的单词统计逻辑效率较低,可以用Python内置的collections.Counter简化实现:

from collections import Counter

@app.route('/wordCount' , methods= ['GET', 'POST'])
def wordCount ():
    results = {}
    if request.method == 'POST':
        wordCount_text = request.form['wordCount_text']
        # 过滤空字符串,split()默认按任意空白分割,自动忽略连续空格
        word_list = [word for word in wordCount_text.split() if word]
        # 直接统计单词出现次数,Counter对象可直接在Jinja2中遍历
        results = Counter(word_list)
        # 如果需要将计数转为字符串,可添加如下代码:
        # results = {word: str(count) for word, count in results.items()}
    return render_template('word_count.html', results=results)

补充说明

你之前尝试的.iteritems()是Python2的写法,Python3中字典的.items()已经返回迭代器,无需使用.iteritems()。但这些尝试无法解决根本问题——变量未定义,必须确保results在所有请求场景下都被传递到模板中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:12:18