Here is my python code

@app.route("/buy", methods=["GET", "POST"])
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.")

            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">

        <button class="btn btn-primary" type="submit">Purchase</button>
{% 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'


I'm new to this, but am working on this PSET myself at the moment. Here's what I think the problem is (feel free to roast me if it's not! ;)):

lookup returns a dictionary with 3 keys: 1.) name 2.) price 3.) symbol.

You're trying to use a key called "stock".

Try using:

price = dictionary["price"]

Hope that solves it. Best of luck with the rest of it!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .