Flask项目中Python list index out of range错误排查求助
问题根源与解决方法
核心问题
你单独测试时fetchall()返回的是包含单个元组的列表:
[('PCKCMH0S', 'English Breakfast', 'Fatty', '3/9/2024', 'BQD3MPHM', '77WWB0BQ', 'QGH6DV8S', 'I4VD1IE7', 'QGH6DV8S')]
而display_table返回的rows和这个结构完全一致——它是一个列表,列表里的第一个元素才是你要的那一行数据(元组)。你直接写rows[4],是在取列表的第5个元素,但列表里只有1个元素,必然触发list index out of range。
修复代码
基础修复
先从rows中取出实际的行数据,再通过索引访问字段:
@app.route('/view_meal', methods=['GET', 'POST']) def view_meal(): if request.method == 'POST': selected_meal_id = request.form['selected_meal'] rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'") # 先取出列表中的行元组,同时判断是否存在数据 if not rows: return "Meal not found", 404 meal_row = rows[0] # 用meal_row访问对应索引的字段 food1 = display_table('food_item', where_condition=f"id = '{meal_row[4]}'") food2 = display_table('food_item', where_condition=f"id = '{meal_row[5]}'") food3 = display_table('food_item', where_condition=f"id = '{meal_row[6]}'") food4 = display_table('food_item', where_condition=f"id = '{meal_row[7]}'") food5 = display_table('food_item', where_condition=f"id = '{meal_row[8]}'") foods = [food1, food2, food3, food4, food5] return render_template('display_meal.html', rows=meal_row, foods=foods) else: rows = display_table('meal') return render_template('view_meal.html', items=rows)
优化建议(可选)
- 用循环简化重复的
display_table调用,减少冗余代码:# 取出第4到第8索引的食物ID food_ids = meal_row[4:9] foods = [display_table('food_item', where_condition=f"id = '{fid}'") for fid in food_ids] - 注意SQL注入风险:直接用字符串拼接SQL语句不安全,建议修改
display_table支持参数化查询,比如:# 示例参数化查询的display_table实现片段 def display_table(table, where_condition=None, params=None): sql = f"SELECT * FROM {table}" if where_condition: sql += f" WHERE {where_condition}" cur.execute(sql, params or ()) return cur.fetchall() # 调用时传参数 rows = display_table('meal', where_condition="id = %s", params=(selected_meal_id,))
内容的提问来源于stack exchange,提问作者jerH
相关产品推荐
相关产品推荐

