DragonOsman

buy route pset7 Finance

Apr 9th, 2017
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. @app.route("/buy", methods=["GET", "POST"])
  2. @login_required
  3. def buy():
  4.     """Buy shares of stock."""
  5.    
  6.     if request.method == "POST":
  7.         # ensure a symbol was submitted
  8.         if not request.form.get("symbol"):
  9.             return apology("symbol required")
  10.        
  11.         # check if symbol is valid
  12.         stock = lookup(request.form.get("symbol"))
  13.         if not stock:
  14.             return apology("symbol does not exist")
  15.        
  16.         # ensure that number of shares entered is not negative
  17.         user_input_shares = int(request.form.get("shares"))
  18.         if user_input_shares < 0:
  19.             return apology("number of shares cannot be negative!")
  20.        
  21.         # check how much cash user has
  22.         users_info = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
  23.         if not users_info:
  24.             return apology("something went wrong when looking up cash amount")
  25.        
  26.         # calculate total price of stock
  27.         total = stock["price"] * user_input_shares
  28.         if total > users_info[0]["cash"]:
  29.             return apology("You don't have enough money!")
  30.            
  31.         # update user's information and total amount of cash in database and send user to Portfolio
  32.         total_cash = users_info[0]["cash"] - total
  33.         db.execute("UPDATE users SET cash=:cash WHERE id=:uid", cash=total_cash, uid=session["user_id"])
  34.        
  35.         db.execute("INSERT INTO user_stocks (stock_name, stock_price, stock_symbol, no_of_shares, user_id) VALUES(:sname, :sprice, :ssymbol, :shares, :uid)",
  36.         sname=stock["name"], sprice=stock["price"], ssymbol=stock["symbol"], shares=user_input_shares, uid=session["user_id"])
  37.            
  38.         return redirect(url_for("index"))
  39.        
  40.     elif request.method == "GET":
  41.         return render_template("buy.html")
Advertisement
Add Comment
Please, Sign In to add comment