Flask使用render_template返回字符串仅执行else分支如何解决
问题原因
你的代码问题出在healthchecker函数的循环逻辑上:
- 函数会遍历
raw字典的所有键值对,每一轮循环都会覆盖health变量的赋值 - 你在循环内看到的控制台打印是每一轮的中间结果,但是函数最终返回的是循环结束后最后一次赋值的
health,也就是raw字典最后一个元素的判断结果,所以才会出现看起来永远只返回else分支结果的情况
修复方案
根据实际需求选择对应修改方式:
需求1:只要有任意一个项存在properties就返回"Yes",全部没有才返回"None"
def healthchecker(): # 先默认赋值为None health = "None" for key,value in raw.items(): if 'properties' in value: # 只要匹配到符合条件的项就修改为Yes,可直接中断循环减少冗余遍历 health = "Yes" break return health return render_template('portlist.html', data = raw, health = healthchecker())
需求2:需要返回每个项对应的健康状态,传到模板中遍历展示
def healthchecker(): health_list = [] for key,value in raw.items(): if 'properties' in value: health_list.append((key, "Yes")) else: health_list.append((key, "None")) return health_list return render_template('portlist.html', data = raw, health_list = healthchecker())
对应模板侧可以循环输出所有项的状态:
{% for item, health in health_list %} <p>{{ item }} 的健康状态:{{ health }}</p> {% endfor %}
内容的提问来源于stack exchange,提问作者Sumit
相关产品推荐
相关产品推荐

