【发布时间】:2021-06-07 19:58:12
【问题描述】:
我正在尝试显示股票组合。任务是访问数据库,然后查找股票的当前价格,显示它、股票的总价值、10000 的剩余现金和总计,这应该根据当前的股票价格而变化。 我尝试了各种方法来访问和显示数据,但我经常遇到错误,我需要帮助,拜托。我还尝试创建一个 for 循环并将数据附加到列表中,但同样没有成功。 错误是: 文件“/home/ubuntu/finance/application.py”,第 58 行,在索引中 current_price=lookup(row["symbol"]["price"]) TypeError:“NoneType”对象不可下标 我的代码如下:
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
#Access the stocks of the current user from DB
rows=db.execute("SELECT symbol, name, sum(shares) as shares FROM stocks WHERE user_id=:user_id ORDER BY symbol", user_id=session["user_id"])
#Check the current price of each stock using the helper function lookup and calculate the total cost of each stock( * number of shares by price)
#add that info to rows and render it on the index page
sum_total_cost=0
for row in rows:
#symbol=row["symbol"]
#current_price=lookup(symbol["price"])
current_price=lookup(row["symbol"]["price"])
total_cost=current_price*(row["shares"])
row["current_price"]=usd(current_price)
row["total_cost"]=usd(total_cost)
sum_total_cost+=total_cost
#Check the current cash of the user
user_id=session["user_id"]
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
return render_template("index.html", rows=rows, cash = cash, grand_total=grand_total)
HTML
{% 扩展“layout.html”%}
{% block title %}
Index
{% endblock %}
{% block main %}
<h2>Portfolio</h2>
<table class="table table-striped">
<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 row in rows %}
<tr>
<td>{{row.symbol}}
<td>{{row.name}}</td>
<td>{{row.shares}}</td>
<td>{{row.current_price}}</td>
<td>{{row.total_cost}}</td>
{% endfor %}
</tr>
<tr>
<th>Cash</th>
<td></td>
<td></td>
<td></td>
<td>{{cash}}</td>
</tr>
<tr>
<th>Grand Total</th>
<td></td>
<td></td>
<td></td>
<td>{{grand_total}}</td>
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
查找函数
def lookup(symbol):
"""Look up quote for symbol."""
# Contact API
try:
api_key = os.environ.get("API_KEY")
url = f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}"
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
quote = response.json()
return {
"name": quote["companyName"],
"price": float(quote["latestPrice"]),
"symbol": quote["symbol"]
}
except (KeyError, TypeError, ValueError):
return None
【问题讨论】:
-
首先,请准确说明您遇到了什么样的“错误”。这是 Python/Flask 错误还是结果不是您想要的?
-
对不起,刚刚编辑了原帖。当前的错误是python,虽然之前尝试了不同的方法,但我能够显示数据,但总价值永远不正确。
-
不应该这
current_price=lookup(row["symbol"]["price"])读`current_price = lookup(row["symbol"])["price"] (close paren move) 因为lookup返回一个dict并且你想要price的值?
标签: python-3.x sqlite flask