I'm on the buy section of pset7's finance. I can submit a quote and get the correct information back. However, when I go to the buy page and try to purchase said stock, I get a 403 error code that I must provide a username. I checked and my database for purchasing a stock isn't updated. Could anyone help me figure out why I'm being kicked out?

Here's my "buy" code in application.py

@app.route("/buy", methods=["GET", "POST"])
def buy():
    """Buy shares of stock"""
    if request.method == "POST":

        # Ensure request to purchase was entered correctly
        if not request.form.get("symbol") or request.form.get("shares"):
            return apology("Missing information from the request", 400)

        # Ensure symbol is valid
        quoted = lookup(request.form.get("symbol"))

        if not quoted:
            return apology("Symbol isn't valid or doesn't exist", 400)

        quantity = int(request.form.get("shares"))
        order = quoted["price"]*quantity

        # Check user's cash amount
        cash = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])

        cash_ready = cash[0]["cash"]

        # If user has enough cash
        if cash_ready >= order:

            #subtract from cash (shares*symbol.price)
            db.execute("UPDATE users SET cash = cash - :order WHERE id = :id", id=session["user_id"], order=order)

            #update price history
            db.execute("INSERT INTO price_history (symbol, price) VALUES (:symbol, :price)", symbol=quoted["symbol"], price=usd(quoted["price"]))

            #update portfolio
            db.execute("INSERT INTO portfolio (symbol, shares, name, id) VALUES (:symbol, :shares, :name, :id)", symbol=quoted["symbol"], shares=quantity, name=quoted["name"], id=session["user_id"])

        #if cash < order, deny purchase
       return render_template("index.html")

        if not cash or cash_ready < order:
            return apology("Sorry insufficient funds", 400)

        return render_template("buy.html")

In the database there's three tables (users, portfolio, and price_history). I've provided screenshots of the two last tables, if this question is more of a database issue.

enter image description here)

enter image description here

  • Ok I figured out the problem (which was actually in buy.html). However, I'm now getting an error message of "Missing information from the request" when I submit the purchase. – MEM Nov 4 '18 at 2:04
if not request.form.get("symbol") or request.form.get("shares"):

Instead of a negation and an affirmation need two negations:

if not request.form.get("symbol") or not request.form.get("shares"):
  • Thanks so much! Yes now the purchase is going through. The database isn't updating as I planned (the timestamp isn't going through) but I'll look into that piece further.... – MEM Nov 4 '18 at 20:46

You must log in to answer this question.

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