0

For some reason, my buy function will not work. When I try to "buy" a share of stock, it always goes to internal server error. Here is my code:

def buy():

if request.method == "POST":
    
    symbol = request.form.get("symbol")
    shares = request.form.get("shares")
    
    if not symbol:
        return apology ("need stock symbol")
    if not lookup(symbol):
        return apology ("invalid symbol")
    if int(shares) <= 0:
        return apology ("need positive number of shares")
        
    balance = db.execute("SELECT cash FROM users WHERE id = :user_id",  user_id = session["user_id"])[0]["cash"]
    
    total = lookup(symbol)["price"]*int(shares);
    
    if total > balance:
        return apology ("not enough cash")
    
    db.execute("INSERT INTO transactions (user_id, type, symbol, shares, price) VALUES (?,?,?,?,?)")
    
    db.execute("UPDATE users SET cash = :balance - :total WHERE id = :user_id", user_id = session["user_id"])
    
    portfolio = db.execute("SELECT shares FROM portfolio WHERE user_id = :user_id AND symbol =:symbol", user_id = session["user_id"],  symbol = symbol)
    
    if len(portfolio) == 1:
        shares = portfolio[0]["shares"] + int(shares)
        db.execute("UPDATE portfolio SET shares = :shares WHERE user_id = :user_id AND symbol = :symbol", user_id = session["user_id"], symbol = symbol, shares = shares)

    else:
        db.execute("INSERT INTO portfolio (user_id, symbol, shares) VALUES (:user_id, :symbol, :shares)", user_id = session["user_id"], symbol = symbol, shares = int(shares))
    return redirect("/")
    
else:
    return render_template("buy.html")

Can someone please help? I have no idea what is wrong.

  • Can you also post the Flask traceback in the terminal? – Ashen Gunaratne Jul 14 '20 at 5:27
0

I realise your question was posted a month ago but, in this query:

db.execute("UPDATE users SET cash = :balance - :total WHERE id = :user_id", user_id = session["user_id"])

You give a value to :user_id, but no values for :balance or :total.

You must log in to answer this question.

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