|
| 1 | +import os |
| 2 | + |
| 3 | +from cs50 import SQL |
| 4 | +from flask import Flask, flash, redirect, render_template, request, session |
| 5 | +from flask_session import Session |
| 6 | +from werkzeug.security import check_password_hash, generate_password_hash |
| 7 | + |
| 8 | +from helpers import apology, login_required, lookup, usd |
| 9 | + |
| 10 | +# Configure application |
| 11 | +app = Flask(__name__) |
| 12 | + |
| 13 | +# Custom filter |
| 14 | +app.jinja_env.filters["usd"] = usd |
| 15 | + |
| 16 | +# Configure session to use filesystem (instead of signed cookies) |
| 17 | +app.config["SESSION_PERMANENT"] = False |
| 18 | +app.config["SESSION_TYPE"] = "filesystem" |
| 19 | +Session(app) |
| 20 | + |
| 21 | +# Configure CS50 Library to use SQLite database |
| 22 | +db = SQL("sqlite:///finance.db") |
| 23 | + |
| 24 | + |
| 25 | +@app.after_request |
| 26 | +def after_request(response): |
| 27 | + """Ensure responses aren't cached""" |
| 28 | + response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" |
| 29 | + response.headers["Expires"] = 0 |
| 30 | + response.headers["Pragma"] = "no-cache" |
| 31 | + return response |
| 32 | + |
| 33 | + |
| 34 | +@app.route("/") |
| 35 | +@login_required |
| 36 | +def index(): |
| 37 | + """Show portfolio of stocks""" |
| 38 | + user_id = session["user_id"] |
| 39 | + |
| 40 | + stocks = db.execute("SELECT symbol, price, SUM(shares) as totalShares FROM transactions WHERE user_id = ? GROUP BY symbol", user_id) |
| 41 | + cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"] |
| 42 | + |
| 43 | + total = cash |
| 44 | + |
| 45 | + for stock in stocks: |
| 46 | + total += stock["price"] * stock["totalShares"] |
| 47 | + |
| 48 | + return render_template("index.html", stocks=stocks, cash=cash, usd=usd, total=total) |
| 49 | + |
| 50 | + |
| 51 | +@app.route("/buy", methods=["GET", "POST"]) |
| 52 | +@login_required |
| 53 | +def buy(): |
| 54 | + """Buy shares of stock""" |
| 55 | + if request.method == "POST": |
| 56 | + symbol = request.form.get("symbol").upper() |
| 57 | + item = lookup(symbol) |
| 58 | + |
| 59 | + if not symbol: |
| 60 | + return apology("Please enter a symbol!") |
| 61 | + elif not item: |
| 62 | + return apology("Invalid Symbol!") |
| 63 | + |
| 64 | + try: |
| 65 | + shares = int(request.form.get("shares")) |
| 66 | + except: |
| 67 | + return apology("Shares should be an integer!") |
| 68 | + |
| 69 | + if shares <= 0: |
| 70 | + return apology("Shares should be positive integer!") |
| 71 | + |
| 72 | + user_id = session["user_id"] |
| 73 | + cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"] |
| 74 | + |
| 75 | + item_price = item["price"] |
| 76 | + total_price = item_price * shares |
| 77 | + |
| 78 | + if cash < total_price: |
| 79 | + return apology("Not Enough Money!") |
| 80 | + else: |
| 81 | + db.execute("UPDATE users SET cash=? WHERE id=?", cash - total_price, user_id) |
| 82 | + db.execute("INSERT INTO transactions (user_id, shares, price, type, symbol) VALUES (?, ?, ?, ?, ?)", |
| 83 | + user_id, shares, item_price, 'buy', symbol) |
| 84 | + return redirect('/') |
| 85 | + |
| 86 | + else: |
| 87 | + return render_template('buy.html') |
| 88 | + |
| 89 | + |
| 90 | +@app.route("/history") |
| 91 | +@login_required |
| 92 | +def history(): |
| 93 | + """Show history of transactions""" |
| 94 | + user_id = session["user_id"] |
| 95 | + transactions = db.execute("SELECT type, symbol, price, shares, time FROM transactions WHERE user_id = ?", user_id) |
| 96 | + |
| 97 | + return render_template("history.html", transactions=transactions, usd=usd) |
| 98 | + |
| 99 | + |
| 100 | +@app.route("/login", methods=["GET", "POST"]) |
| 101 | +def login(): |
| 102 | + """Log user in""" |
| 103 | + |
| 104 | + # Forget any user_id |
| 105 | + session.clear() |
| 106 | + |
| 107 | + # User reached route via POST (as by submitting a form via POST) |
| 108 | + if request.method == "POST": |
| 109 | + # Ensure username was submitted |
| 110 | + if not request.form.get("username"): |
| 111 | + return apology("must provide username", 403) |
| 112 | + |
| 113 | + # Ensure password was submitted |
| 114 | + elif not request.form.get("password"): |
| 115 | + return apology("must provide password", 403) |
| 116 | + |
| 117 | + # Query database for username |
| 118 | + rows = db.execute( |
| 119 | + "SELECT * FROM users WHERE username = ?", request.form.get("username") |
| 120 | + ) |
| 121 | + |
| 122 | + # Ensure username exists and password is correct |
| 123 | + if len(rows) != 1 or not check_password_hash( |
| 124 | + rows[0]["hash"], request.form.get("password") |
| 125 | + ): |
| 126 | + return apology("invalid username and/or password", 403) |
| 127 | + |
| 128 | + # Remember which user has logged in |
| 129 | + session["user_id"] = rows[0]["id"] |
| 130 | + |
| 131 | + # Redirect user to home page |
| 132 | + return redirect("/") |
| 133 | + |
| 134 | + # User reached route via GET (as by clicking a link or via redirect) |
| 135 | + else: |
| 136 | + return render_template("login.html") |
| 137 | + |
| 138 | + |
| 139 | +@app.route("/logout") |
| 140 | +def logout(): |
| 141 | + """Log user out""" |
| 142 | + |
| 143 | + # Forget any user_id |
| 144 | + session.clear() |
| 145 | + |
| 146 | + # Redirect user to login form |
| 147 | + return redirect("/") |
| 148 | + |
| 149 | + |
| 150 | +@app.route("/quote", methods=["GET", "POST"]) |
| 151 | +@login_required |
| 152 | +def quote(): |
| 153 | + """Get stock quote.""" |
| 154 | + if (request.method == "POST"): |
| 155 | + symbol = request.form.get('symbol') |
| 156 | + |
| 157 | + if not symbol: |
| 158 | + return apology("Write a symbol!") |
| 159 | + |
| 160 | + item = lookup(symbol) |
| 161 | + |
| 162 | + if not item: |
| 163 | + return apology("Wrong symbol!") |
| 164 | + |
| 165 | + return render_template('quoted.html', item=item, usd=usd) |
| 166 | + |
| 167 | + else: |
| 168 | + return render_template('quote.html') |
| 169 | + |
| 170 | + |
| 171 | +@app.route("/register", methods=["GET", "POST"]) |
| 172 | +def register(): |
| 173 | + """Register user""" |
| 174 | + if (request.method == "POST"): |
| 175 | + username = request.form.get("username") |
| 176 | + password = request.form.get("password") |
| 177 | + confirmation = request.form.get("confirmation") |
| 178 | + |
| 179 | + if not username or not password or not confirmation or password != confirmation: |
| 180 | + return apology("You have done something wrong! Please try again.") |
| 181 | + |
| 182 | + try: |
| 183 | + hash = generate_password_hash(password) |
| 184 | + db.execute("INSERT INTO users (username, hash) VALUES (?, ?)", username, hash) |
| 185 | + |
| 186 | + return redirect('/') |
| 187 | + |
| 188 | + except: |
| 189 | + return apology("Username has already been exist") |
| 190 | + |
| 191 | + else: |
| 192 | + return render_template("register.html") |
| 193 | + |
| 194 | + |
| 195 | +@app.route("/sell", methods=["GET", "POST"]) |
| 196 | +@login_required |
| 197 | +def sell(): |
| 198 | + """Sell shares of stock""" |
| 199 | + if request.method == "POST": |
| 200 | + user_id = session["user_id"] |
| 201 | + symbol = request.form.get("symbol") |
| 202 | + shares = int(request.form.get("shares")) |
| 203 | + |
| 204 | + if shares <= 0: |
| 205 | + return apology("Shares must be positive!") |
| 206 | + |
| 207 | + item_price = lookup(symbol)["price"] |
| 208 | + price = shares * item_price |
| 209 | + |
| 210 | + owned_shares = db.execute("SELECT SUM(shares) FROM transactions WHERE user_id = ? AND symbol = ? ", user_id, symbol)[0]["SUM(shares)"] |
| 211 | + |
| 212 | + if owned_shares < shares: |
| 213 | + return apology("You don't have enough shares!") |
| 214 | + |
| 215 | + current_cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"] |
| 216 | + db.execute("UPDATE users SET cash = ? WHERE id = ?", current_cash + price, user_id) |
| 217 | + db.execute("INSERT INTO transactions (user_id, shares, price, type, symbol) VALUES (?, ?, ?, ?, ?)", |
| 218 | + user_id, -shares, item_price, "sell", symbol) |
| 219 | + return redirect('/') |
| 220 | + |
| 221 | + else: |
| 222 | + user_id = session["user_id"] |
| 223 | + symbols = db.execute("SELECT symbol FROM transactions WHERE user_id = ? GROUP BY symbol", user_id) |
| 224 | + |
| 225 | + return render_template("sell.html", symbols=symbols) |
0 commit comments