Here is my python code
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "GET":
return render_template ("buy.html")
elif request.method == "POST":
stock = request.form.get("stock_to_buy")
quantity = request.form.get("quantity")
dictionary = lookup(stock)
price = dictionary[stock]
total_price = price * quantity
cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
if not stock:
return apology("Please enter the stock you wish to buy.")
elif not quantity:
return apology("Please specify the quantity of the stock you wish to buy.")
elif not dictionary:
return apology("Please enter a valid stock.")
elif total_price > cash:
return apology("Not enough cash to buy stocks.")
else:
cash = cash - price
db.execute("INSERT INTO user_stocks (stocks, quantity) VALUES (?, ?) WHERE user_id = ?", stock, quantity, session["user_id"])
return render_template ("buy.html")
action = "buy"
db.execute("INSERT INTO history (stock, quantity, time, action) VALUES (?, ?, ?, ?) WHERE user_id = ?", stock, quantity, datetime('now', 'localtime'), action, session["user_id"])
Here is my html code.
{% extends "layout.html" %}
{% block title %}
Buy stocks
{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="stock_to_buy" placeholder="Symbol" type="text">
<input autocomplete="off" autofocus class="form-control" name="quantity" placeholder="Quantity" type="number" min = "0">
</div>
<button class="btn btn-primary" type="submit">Purchase</button>
</form>
{% endblock %}
The error message in the terminal is as such. File "/home/ubuntu/pset9/finance/application.py", line 75, in buy price = dictionary[stock] KeyError: 'AAPL'