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

解决Flask中Jinja2的'get_count'未定义错误及计数显示问题

解决Flask中jinja2.exceptions.UndefinedError: 'get_count' is undefined错误

开发基于Flask的Python应用时,访问本地链接出现上述错误。单独运行计数逻辑的Python脚本可正常输出结果,但HTML页面无法正确显示计数(预期输出:The acceleration count is 4)。

原代码

app.py

import numpy as np
from flask import Flask, render_template, request
app = Flask(__name__)
x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27,
22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11,
12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22,
27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23,
])
@app.route('/')
def main():
    return render_template('index.html')
@app.route('/send', methods=['POST'])
def get_count(id_count):
    sub_lists = np.split(x, np.where(np.diff(x) <0)[0] + 1)
    id_count=0
    id_list = []
    for unit in sub_lists:
      if min(unit) ==0 and max(unit)>20 and len(set(unit)) > 1:
         id_count += 1
         id_list.append(unit)
      return id_count
      return render_template("index.html",get_count(x))

print("Number of counts: ",get_count(x))
if __name__=="__main__":
    app.run(debug=False, port=1223)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<form action="/data" method = "POST">

<h2> flask app for counting accelerations</h2>
    <p>The acceleration count is "{{get_count(x)}}"</p>

</form>
</head>
</html>

问题根源

  • get_count被定义为Flask路由函数,Jinja2模板无法直接调用路由函数
  • 路由函数get_count携带自定义参数id_count,不符合Flask路由函数参数规则
  • 表单action指向/data,但代码中未定义该路由
  • 主路由未计算计数结果并传递给模板,模板错误尝试调用函数获取值

修正后的代码

app.py

import numpy as np
from flask import Flask, render_template, request
app = Flask(__name__)
x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27,
22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11,
12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22,
27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23,
])

# 改为普通工具函数,而非路由函数
def get_count(data):
    sub_lists = np.split(data, np.where(np.diff(data) < 0)[0] + 1)
    id_count = 0
    id_list = []
    for unit in sub_lists:
        # 修正缩进:避免循环内提前return导致遍历终止
        if min(unit) == 0 and max(unit) > 20 and len(set(unit)) > 1:
            id_count += 1
            id_list.append(unit)
    return id_count

@app.route('/')
def main():
    # 计算结果并传递给模板
    acceleration_count = get_count(x)
    return render_template('index.html', count=acceleration_count)

# 可选:保留表单提交触发的路由(对应表单action)
@app.route('/send', methods=['POST'])
def handle_form():
    acceleration_count = get_count(x)
    return render_template('index.html', count=acceleration_count)

print("Number of counts: ", get_count(x))
if __name__ == "__main__":
    app.run(debug=False, port=1223)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Acceleration Counter</title>
</head>
<body>
    <h2>Flask App for Counting Accelerations</h2>
    <!-- 修正表单action为已定义的路由 -->
    <form action="/send" method="POST">
        <button type="submit">Calculate Count</button>
    </form>
    <!-- 直接引用模板传递的变量 -->
    <p>The acceleration count is "{{ count }}"</p>
</body>
</html>

关键修改说明

  1. 重构get_count为普通函数:路由函数无法被Jinja2模板直接调用,改为工具函数后可在Python代码内部计算结果
  2. 修正路由参数:移除路由函数的自定义参数,符合Flask路由函数参数规则
  3. 对齐表单与路由:将表单action指向已定义的/send路由
  4. 主路由传递结果:在主路由中调用get_count计算结果,将变量count传递给模板,模板直接引用该变量
  5. 修复循环逻辑:将return移出循环内部,确保遍历所有子列表完成计数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:15:27