Flask结合SQLite3实现股票组合展示时出现NoneType不可下标报错
问题根因
两处核心逻辑错误直接触发当前报错:
- 对
lookup函数的参数、返回值调用逻辑完全颠倒:lookup需要传入股票代码字符串才能返回包含价格、名称的字典,现在的写法是对row["symbol"](本身是字符串类型的股票代码)额外加["price"]下标,相当于对普通字符串取字典键,不符合Python语法规则;如果这步侥幸通过,后续lookup因接口异常、股票代码无效返回None时,对None对象取下标就会触发你看到的TypeError: 'NoneType' object is not subscriptable。 - 没有做
lookup返回空值的兼容处理:lookup函数在接口请求失败、代码无效时会返回None,此时直接取值、做数值计算必然崩溃。
具体修复步骤
1. 修正application.py中循环内的行情查询逻辑
原有错误代码:
current_price=lookup(row["symbol"]["price"]) total_cost=current_price*(row["shares"])
调整为正确逻辑,先做空值判断再取值:
for row in rows: # 直接传入字符串格式的股票代码调用接口 symbol_info = lookup(row["symbol"]) # 接口返回空值时跳过,避免整页崩溃 if not symbol_info: continue current_price = symbol_info["price"] total_cost = current_price * row["shares"] # 用实时查询到的官方名称替换数据库存储的历史名称,避免更名后数据不一致 row["name"] = symbol_info["name"] row["current_price"] = usd(current_price) row["total_cost"] = usd(total_cost) sum_total_cost += total_cost
2. 修正用户现金、总资产的格式化逻辑
原有代码拿到现金值后直接传到模板,没有做格式统一,调整为:
user = db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=user_id) cash = user[0]["cash"] grand_total = cash + sum_total_cost # 统一做美元格式转换 formatted_cash = usd(cash) formatted_grand_total = usd(grand_total) return render_template("index.html", rows=rows, cash=formatted_cash, grand_total=formatted_grand_total)
3. 修正HTML模板的表格结构错误
原有模板把</tr>标签放在了for循环外部,还存在单元格未闭合的问题,调整为:
<tbody> {% for row in rows %} <tr> <td>{{ row.symbol }}</td> <td>{{ row.name }}</td> <td>{{ row.shares }}</td> <td>{{ row.current_price }}</td> <td>{{ row.total_cost }}</td> </tr> {% endfor %} <tr> <th>Cash</th> <!-- 空单元格加列合并属性,保证表格对齐 --> <td colspan="4"></td> <td>{{ cash }}</td> </tr> <tr> <th>Grand Total</th> <td colspan="4"></td> <td>{{ grand_total }}</td> </tr> </tbody>
额外优化点
- 数据库聚合查询持仓时,加
HAVING sum(shares) > 0过滤0持仓行,避免无意义的数据展示。 - 可以删除数据库中冗余存储的股票名称字段,每次展示时用
lookup返回的名称动态更新即可,减少数据不一致风险。
内容的提问来源于stack exchange,提问作者Plain Jane
相关产品推荐
相关产品推荐

