@app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): """Buy shares of stock."""
session["user_id"]
#check the way of request
if request.method == "GET":
return render_template("buy.html")
#check the way of request
elif request.method == "POST":
#extract the symbol from form
quoted = lookup(request.form.get("quote"))
#vailidity of symbol
if quoted == None:
return apology("Invalid Symbol")
#extracting shares
shares = request.form.get("shares")
if not shares:
return apology("Enter some shares")
#checking for the cash using id
cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
#user can afford or not
price = quoted['price']
if price * shares > cash:
return apology("can't afford")
#updating the users cash if stock buyed
balance = cash - price
db.execute("UPDATE users SET cash = :bal WHERE id = :id",bal = balance, id = session["user_id"] )
#including the transaction in database
history = db.execute("INSERT INTO history (username_id, datetime, symbol, price, share, cost) VALUES (:user, :dt, :symbol, :price, :share, :costs)", user = session["user_id"], dt = datetime.now(), symbol = quoted['symbol'], price = usd(quoted['price']), share = shares, costs = cost)
return render_template(url_for("index"))
*
in there, so I guess it's theif price * shares > cash:
line