Advertisement
DragonOsman

pset7 finance sell route

Mar 19th, 2017
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. @login_required
  2. def sell():
  3.     """Sell shares of stock."""
  4.     if request.method == "POST":
  5.         # ensure that entered stock symbol is valid
  6.         stock = lookup(request.form.get("symbol"))
  7.         if not stock:
  8.             return apology("invalid symbol!")
  9.        
  10.         # check if user has shares of that stock
  11.         stock_query = db.execute("SELECT * FROM user_stocks WHERE user_id=:uid AND stock_symbol=:ssymbol", uid=session["user_id"], ssymbol=stock["symbol"])
  12.         for i in range(len(stock_query)):
  13.             if stock_query[i]["stock_symbol"] != request.form.get("symbol"):
  14.                 return apology("You don't have any shares of that stock!")
  15.        
  16.         # ensure that user has enough shares of the stock
  17.         total_shares = 0;
  18.         for i in range(len(stock_query)):
  19.             total_shares += stock_query[i]["no_of_shares"]
  20.        
  21.         # check if subtracting that number of shares will leave the user with no shares of that stock left
  22.         # or if it leaves him/her with the amount he/she wants
  23.         shares_to_sell = int(request.form.get("shares"))
  24.         for i in range(len(stock_query)):
  25.             if shares_to_sell > 0:
  26.                 if total_shares < shares_to_sell:
  27.                     return apology("You don't have enough shares of that stock for this!")
  28.                 elif total_shares >= shares_to_sell or stock_query[i]["no_of_shares"] >= shares_to_sell:
  29.                     db.execute("INSERT INTO user_stocks (stock_name, stock_price, stock_symbol, no_of_shares, user_id) VALUES(:sname, :sprice, :ssymbol, :shares, :uid)",
  30.                     sname=stock_query[i]["stock_name"], sprice=stock_query[i]["stock_price"], ssymbol=request.form.get("symbol"), shares=(-1 * shares_to_sell), uid=session["user_id"])
  31.             else:
  32.                 return apology("The shares you have to sell has to be a positive number greater than 0!")
  33.                
  34.         user_cash = db.execute("SELECT cash FROM users WHERE id=:uid", uid=session["user_id"])
  35.         db.execute("UPDATE users SET cash=:cash WHERE id=:uid", cash=user_cash[0]["cash"] + (stock["price"] * int(request.form.get("shares"))), uid=session["user_id"])
  36.        
  37.         return redirect(url_for("index"))
  38.        
  39.     elif request.method == "GET":
  40.         return render_template("sell.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement