python - Error while displaying data from SQLite3 using Flask
问题描述
I am creating an app for buying stocks using an API. The goal is to show a portfolio with the stocks bought displaying the current price. I have been working on the index function for days but I am constantly having errors. I would be grateful for any hints and help. Needless to say, I am a newbie and self-learner. I having the following errors: File "/home/ubuntu/finance/helpers.py", line 34, in decorated_function return f(*args, **kwargs) File "/home/ubuntu/finance/application.py", line 57, in index shares=stocks[0]["shares"] KeyError: 'shares'
enter code here@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
user_id=session["user_id"]
stocks= db.execute("SELECT symbol, sum(shares) as total_cost FROM stocks WHERE user_id=:user_id GROUP BY symbol", user_id=user_id)
grand_total=0
stocks_data=[]
for stock_data in stocks:
symbol=stocks[0]["symbol"]
shares=stocks[0]["shares"]
name=stocks[0]["name"]
price=lookup(symbol)
total_cost=shares*price["price"]
grand_total+=total_cost
stocks_data.append(stock_data)
return render_template("index.html", stocks=stocks, stocks_data=stocks_data )
Html is here
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<h2>Portfolio</h2>
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Shares</th>
<th>Price</th>
<th>Total Cost</th>
</tr>
</thead>
<tbody>
<!-- TODO: Loop through the database to display all transactions and the balance -->
{% for stock_data in stocks_data %}
<tr>
<td>{{stock_data.symbol}}
<td>{{stock_data.name}}</td>
<td>{{stock_data.shares}}</td>
<td>{{(stock_data["price"])|usd}}</td>
<td>{{(stock_data["total_cost"])|usd}}</td>
</tr>
{% endfor %}
<tr>
<th>CASH</th>
<td>
</td>
<td></td>
<td></td>
<td></td>
<td>{{cash}}</td>
</tr>
<tr>
<th>Grand Total</th>
<td>
</td>
<td></td>
<td></td>
<td></td>
<td>{{grand_total|usd}}</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
解决方案
sum(shares)
is aliased to total_cost
here stocks= db.execute("SELECT symbol, sum(shares) as total_cost.....
. There is not key named shares
; it is named total_cost
.Either change the alias in the sql or change the key name here shares=stocks[0]["shares"]
.
推荐阅读
- cloud - Talend Cloud 创建集群
- oracle - Oracle ORA-00904 错误:标识符无效
- asp.net-core - 访问 .Net Core Web 应用程序 (.NET 5) 中的 html 标签
- python - Python - 读取文件,重新排列日期并将年份从 yy 更改为 yyyy
- elasticsearch - Elasticsearch 3 of 280 shards failed 错误 - 有没有人见过这样的事情并且知道如何修复它?
- python - python 2d list 根据最接近的值获取排序数组
- pandas - 使用 dockerfile 为 ARM/V7 架构安装 pandas 卡住了
- python - discord.py:Bot 缺少权限怎么办?
- ios - Core Image 可以进行亚像素渲染吗?
- c# - 在使用 Moq 进行单元测试期间,如何从授权过滤器的上下文中访问所需的服务?