Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- if request.method =="POST":
- # use lookup to verify the stock
- stock = lookup(request.form.get("stock"))
- if not stock:
- return apology("The stock you entered does not exist.", 403)
- # check if shares are valid integers
- try:
- shares = int(request.form.get("shares"))
- if shares <= 0:
- return apology("Enter a positive number", 403)
- except ValueError:
- return apology("Enter a positive number", 403)
- # check if user has enough cash
- # db.execute returns a list of dictionaries which needs to be accessed and then comapared
- cash = db.execute("SELECT * FROM users WHERE id = :id", \
- id = session["user_id"])
- if cash[0]["cash"] < (shares * float(stock["price"])) or not cash:
- return apology("You don't have enough money")
- else:
- # add to database in portfolio
- db.execute("INSERT INTO portfolio (user_id, symbol, shares, price) VALUES(:user_id, :symbol, :shares, :price)", \
- user_id = session["user_id"], symbol = request.form.get("stock"), shares = request.form.get("shares"), price = shares*float(stock["price"]))
- # update cash in users table UPDATE users SET cash = cash - 50 WHERE id = :id
- db.execute("UPDATE users SET cash = cash - :purchase WHERE id = :id", \
- id = session["user_id"], purchase = shares*float(stock["price"]))
- # redirect to portfolio page
- return redirect("/")
- else:
- return render_template("buy.html")
Add Comment
Please, Sign In to add comment