I am trying to work on pset7, but am having a problem printing it out to the screen in the table format. I have all the values I need (the values I have are correct), but just can't figure out how to display these last 2 attributes on the html table. (I'm not worried about Your Current Cash Balance and Grand Total, that should be easy after this).
I just basically (in sql / db.execute) grouped by symbol and then looked up the price for each symbol (thanks to lookup
function) and stored each symbol's current price in the currentprices
list so I can iterate through it in HTML / Jinja. Thanks for any guidance
Python (using flask micro-framework):
@app.route("/")
@login_required
def index():
stocks = db.execute("SELECT stock, symbol, Sum(quantity) AS quantities FROM portfolio WHERE user_id_fk = :user_id_fk GROUP BY stock, symbol ORDER BY stock",
user_id_fk = session["user_id"])
currentprices = []
# get current price for each group (ie AAPL) with help from lookup function (which remember, returns a dict)
for stock in stocks:
symbol = str(stock["symbol"])
quote = lookup(symbol)
currentprices.append(quote['price'])
cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
# render the template with the stored result sets from queries
return render_template("index.html", stocks = stocks, cash = cash, currentprices = currentprices)
Here's the index.html / Jinja2 code:
{% extends "layout.html" %}
{% block title %}
Your Portfolio
{% endblock %}
{% block main %}
<table>
<tr>
<th>Stock</th>
<th>Shares</th>
<th>Current Value</th>
<th>Total Value</th>
</tr>
{% for stock in stocks %}
<tr>
<td>{{ stock["stock"] }}</td>
<td>{{ stock["quantities"] }}</td>
</tr>
{% endfor %}
{% for currentprice in currentprices %}
<tr>
<td>current value is {{ currentprice }}</td>
<td>total value (shares * price) here</td>
</tr>
{% endfor %}
</table>
output: