· 5 years ago · Nov 19, 2020, 10:50 PM
1@app.route("/buy", methods=["GET", "POST"])
2@login_required
3def buy():
4 """Buy shares of stock"""
5 if request.method == "GET":
6 return render_template("buy.html")
7
8 else:
9 # render apology if symbol is blank
10 if not request.form.get("symbol"):
11 return apology("Please enter a symbol", 403)
12
13 # render apology if shares is blank
14 if not request.form.get("shares"):
15 return apology("Please enter a valid number of shares", 403)
16
17 # lookup symbol and store result in variable
18 info = lookup(request.form.get("symbol"))
19
20 # render apology if stock symbol doesn't exist
21 if info is None:
22 return apology("Please enter a valid stock symbol")
23
24 # check if number of shares is entered and positive number
25 shares = float(request.form.get("shares"))
26 if not shares >= 1:
27 return apology("Please enter at least one share")
28
29 # log time user purchased stock
30 now = datetime.datetime.now()
31
32 # if table doesn't exist for that username, create table for current user's transactions
33 # alternative idea: # if db.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = ?", session["user_id"]) is 0:
34 user_id = session["user_id"]
35 db.execute(f"CREATE TABLE IF NOT EXISTS {user_id} (username VARCHAR PRIMARY KEY, stock VARCHAR, shares REAL, transaction VARCHAR, purchase_date DATETIME, purchase_price REAL, cash REAL);")
36
37 # create variables for username, stock price, transaction cost, and user's current cash amount
38 username = db.execute("SELECT username FROM users WHERE id = ?", session["user_id"])[0]["username"]
39 price = info["price"]
40 cost = price * shares
41 cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]["cash"]
42
43 # if cost of purchase is greater than user's cash amount, return apology
44 if cost > cash:
45 return apology("Insufficient funds", 403)
46
47 # calculate remaining cash and insert transaction info into user's transaction table
48 cash_remaining = cash - cost
49 db.execute(f"INSERT INTO {user_id} (username, stock, shares, transaction, purchase_date, purchase_price, cash) VALUES (?, ?, ?, ?, ?, ?, ?);", username, info["symbol"], shares, "bought", now, price, cash_remaining)
50
51 # update the users table to reflect current user's remaining cash
52 db.execute("UPDATE users SET cash = :cash WHERE user_id = :user", cash=cash_remaining, user=user_id)
53 return redirect("/")
54