Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- """Buy shares of stock."""
- if request.method == "POST":
- # ensure a symbol was submitted
- if not request.form.get("symbol"):
- return apology("symbol required")
- # check if symbol is valid
- stock = lookup(request.form.get("symbol"))
- if not stock:
- return apology("symbol does not exist")
- # ensure that number of shares entered is not negative
- user_input_shares = int(request.form.get("shares"))
- if user_input_shares < 0:
- return apology("number of shares cannot be negative!")
- # check how much cash user has
- users_info = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
- if not users_info:
- return apology("something went wrong when looking up cash amount")
- # calculate total price of stock
- total = stock["price"] * user_input_shares
- if total > users_info[0]["cash"]:
- return apology("You don't have enough money!")
- # update user's information and total amount of cash in database and send user to Portfolio
- total_cash = users_info[0]["cash"] - total
- db.execute("UPDATE users SET cash=:cash WHERE id=:uid", cash=total_cash, uid=session["user_id"])
- db.execute("INSERT INTO user_stocks (stock_name, stock_price, stock_symbol, no_of_shares, user_id) VALUES(:sname, :sprice, :ssymbol, :shares, :uid)",
- sname=stock["name"], sprice=stock["price"], ssymbol=stock["symbol"], shares=user_input_shares, uid=session["user_id"])
- return redirect(url_for("index"))
- elif request.method == "GET":
- return render_template("buy.html")
Advertisement
Add Comment
Please, Sign In to add comment