Advertisement
callyb

pset7 buy

Mar 18th, 2017
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. @app.route("/buy", methods=["GET", "POST"])
  2. @login_required
  3. def buy():
  4. """Buy shares of stock."""
  5. if request.method == "GET":
  6. return render_template("buy.html")
  7.  
  8. # if user reached route via POST
  9. if request.method == "POST":
  10. # ensure symbol was submitted
  11. if not request.form.get("symbol") and request.form.get("number_stocks"):
  12. return apology("symbol required")
  13.  
  14. else:
  15. #lookup the stock using the symbol and define vars
  16. details = lookup(request.form.get("symbol"))
  17. symbol = request.form.get("symbol")
  18. price = details["price"]
  19. quantity = int(request.form.get("number_stocks"))
  20. total = price * quantity
  21. user = session["user_id"]
  22.  
  23.  
  24. #ensure the stock is valid
  25. if price == None:
  26. return apology("this stock is not valid")
  27.  
  28. else:
  29. #get cost of stocks and deduct from balance in users account
  30. sum_req = round(price * quantity,2)
  31. balance = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
  32. balance = round(balance[0]['cash'])
  33. remaining = balance - sum_req
  34.  
  35. if balance < sum_req:
  36. return apology("You do not have sufficient funds for this transaction, please try again")
  37.  
  38. else:
  39. #insert transaction into 'transactions' table
  40. db.execute ("UPDATE users SET cash = :cash WHERE id = :id", cash = remaining, id = session["user_id"])
  41. db.execute ("INSERT INTO 'transactions' (users_id, symbol, number, price, date, total_cost) VALUES (user, symbol, quantity, price, datetime('now'), total)")
  42.  
  43. #check if stock is already in the 'portfolio' table
  44. existing_symbol = db.execute ("SELECT symbol = :symbol, number = :number FROM 'users' WHERE users_id = :id", symbol = symbol, number = number, id = user)
  45. #if so add new stock to existing quantity
  46. if existing_symbol:
  47. db.execute ("UPDATE 'portfolio' SET number = number + :quantity, current_value = :new_value where id = :id", quantity=quantity, new_value = (number +quantity)*price, id=user)
  48.  
  49. #if not insert new record
  50. else:
  51. db.execute ("INSERT INTO 'portfolio' (users_id, symbol, number, current_value) VALUES (users_id, symbol, number, current_values)")
  52. #placeholder for now
  53. return render_template("success.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement