I'm working on pset8 cs50 finance and I'm encountering a runtime error with buy. I've gotten both register and quote to work without issue so I've tried comparing my code to check for incorrect syntax, but have yet to find an issue. My code for buy and the .schema commands for both tables are included below. I would truly appreciate it if someone could take a look and either tell me what I'm doing wrong or point me in the direction of a good reasource.
application.py:
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
if request.method == "POST":
#was a symbol submitted
if not request.form.get("symbol"):
return apology("You must submit a stock symbol", 403)
#was an amount submitted
if not request.form.get("shares"):
return apology("You must submit how many shares you would like to purchase", 403)
BInfo = lookup(request.form.get("symbol"))
#was a correct symbol submitted
if len(BInfo) == 0:
return apology("you must submit a valid stock symbol", 403)
shares = request.form.get("shares")
amount = BInfo["price"] * (float(shares))
#affordable
cashcheck = db.execute("SELECT cash FROM users WHERE id = :user", user=session["user_id"])
cash = cashcheck[0]
cashval = cash['cash']
check = cashval - amount
if check < 0:
return apology("you are currently unable to afford these number of shares", 403)
#update stocks owned by inserting what they bought
db.execute("INSERT INTO stocks (symbol, name, shares, userID, price) VALUES (:symbol, :name, :shares, :price, :user)",
symbol=BInfo["symbol"], name=BInfo["name"], shares=shares, price=BInfo["price"], user=session["user_id"])
spent = cashcheck - amount
db.execute("UPDATE users SET cash = :amount", amount=spent)
return render_template("bought.html")
else:
return render_template("buy.html")
.schema users:
CREATE TABLE IF NOT EXISTS 'users' ('id' INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL, 'username' TEXT NOT NULL, 'hash' TEXT NOT
NULL, 'cash' NUMERIC NOT NULL DEFAULT 10000.00 ); CREATE UNIQUE INDEX
'username' ON "users" ("username");
.schema stocks:
CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT,
symbol TEXT NOT NULL, name TEXT NOT NULL, shares INTEGER NOT NULL, price NUMERIC NOT NULL, userID INTEGER, CONSTRAINT FK_userstock FOREIGN KEY (userID) REFERENCES users(id));Copy & Paste from terminal window:
File "/home/ubuntu/pset8/finance/application.py", line 82, in buy
symbol=BInfo["symbol"], name=BInfo["name"], shares=shares, price=BInfo["price"], user=session["user_id"])
File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator
return f(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 365, in execute
raise e
RuntimeError: FOREIGN KEY constraint failed
INFO:werkzeug:192.168.206.42 - - [16/Jun/2020 10:55:27] "POST /buy HTTP/1.0" 500 -