· 6 years ago · Mar 27, 2020, 03:00 PM
1import os
2
3from cs50 import SQL
4from flask import Flask, flash, jsonify, redirect, render_template, request, session
5from flask_session import Session
6from tempfile import mkdtemp
7from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
8from werkzeug.security import check_password_hash, generate_password_hash
9
10from helpers import apology, login_required, lookup, usd
11
12# Configure application
13app = Flask(__name__)
14
15# Ensure templates are auto-reloaded
16app.config["TEMPLATES_AUTO_RELOAD"] = True
17
18# Ensure responses aren't cached
19@app.after_request
20def after_request(response):
21 response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
22 response.headers["Expires"] = 0
23 response.headers["Pragma"] = "no-cache"
24 return response
25
26# Custom filter
27app.jinja_env.filters["usd"] = usd
28
29# Configure session to use filesystem (instead of signed cookies)
30app.config["SESSION_FILE_DIR"] = mkdtemp()
31app.config["SESSION_PERMANENT"] = False
32app.config["SESSION_TYPE"] = "filesystem"
33Session(app)
34
35# Configure CS50 Library to use SQLite database
36db = SQL("sqlite:///finance.db")
37
38# Make sure API key is set
39if not os.environ.get("API_KEY"):
40 raise RuntimeError("API_KEY not set")
41
42
43@app.route("/", methods=["GET"])
44@login_required
45def index():
46 """Show portfolio of stocks"""
47 if request.method == "GET":
48 # pass in value of a single stock currently, how many shares user has, total amount user has, go to database and look stuff, this is only get method, no post
49 # get which user is here
50 data_user = db.execute("SELECT username, cash FROM users WHERE id = ?", session["user_id"])
51 print(data_user[0]["username"], data_user[0]["cash"])
52
53 lis = db.execute("SELECT symbol, amount FROM stocks WHERE whobought = %s", data_user[0]["username"])
54 for i in lis:
55 print(i)
56 print("---------_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_-----_")
57 # now I have a list of all the symbols and the amount that the user has... I wanna add another thing to the list, which is current value, but first lets check if everythings is well
58 return render_template("index.html", cash = int(data_user[0]["cash"]))
59
60
61@app.route("/buy", methods=["GET", "POST"])
62@login_required
63def buy():
64 """Buy shares of stock"""
65 if request.method == "POST":
66 # Make sure client has the money
67 amount = float(request.form.get("amount"))
68 stock_buy = lookup(request.form.get("stock"))
69 if not stock_buy:
70 return render_template("notstock.html")
71 else:
72 curr_price = float(stock_buy.get('price'))
73 lis = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"]) # i got a list of 1 dict saying "'cash': 10000"
74 current_cash = float(lis[0]["cash"])
75 if curr_price * amount < current_cash:
76 current_cash -= curr_price * amount
77 db.execute("UPDATE users SET cash = ? WHERE id = ?", current_cash, session["user_id"])
78 # get username from table
79 user = db.execute("SELECT username FROM users WHERE id = ?", session["user_id"])
80 symbol_stock = stock_buy.get('symbol')
81 db.execute("INSERT INTO stocks (whobought, symbol, amount) VALUES (?, ?, ?)", user[0]["username"], stock_buy.get('symbol'), amount)
82 # Redirect user to home page
83 return redirect("/")
84 else:
85 return render_template("lackofmoney.html")
86 else:
87 return render_template("buy.html")
88
89
90@app.route("/history")
91@login_required
92def history():
93 """Show history of transactions"""
94 return apology("TODO")
95
96
97@app.route("/login", methods=["GET", "POST"])
98def login():
99 """Log user in"""
100
101 # Forget any user_id
102 session.clear()
103
104 # User reached route via POST (as by submitting a form via POST)
105 if request.method == "POST":
106
107 # Ensure username was submitted
108 if not request.form.get("username"):
109 return apology("must provide username", 403)
110
111 # Ensure password was submitted
112 elif not request.form.get("password"):
113 return apology("must provide password", 403)
114
115 # Query database for username
116 rows = db.execute("SELECT * FROM users WHERE username = :username",
117 username=request.form.get("username"))
118
119 # Ensure username exists and password is correct
120 if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
121 return apology("invalid username and/or password", 403)
122
123 # Remember which user has logged in
124 session["user_id"] = rows[0]["id"]
125
126 # Redirect user to home page
127 return redirect("/")
128
129 # User reached route via GET (as by clicking a link or via redirect)
130 else:
131 return render_template("login.html")
132
133
134@app.route("/logout")
135def logout():
136 """Log user out"""
137
138 # Forget any user_id
139 session.clear()
140
141 # Redirect user to login form
142 return redirect("/")
143
144
145@app.route("/quote", methods=["GET", "POST"])
146@login_required
147def quote():
148 """Get stock quote."""
149 if request.method == "POST":
150 stock = lookup(request.form.get("stock"))
151 s = stock.get('price')
152 if not stock:
153 return render_template("notstock.html")
154 else:
155 return render_template("valuequote.html", s = s, stock = stock)
156 else:
157 return render_template("quote.html")
158
159
160@app.route("/register", methods=["GET", "POST"])
161def register():
162 """Register user"""
163 if request.method == "POST":
164 # Ensure username was submitted
165 if not request.form.get("username"):
166 return apology("must provide username", 403)
167
168 # Ensure password was submitted
169 elif not request.form.get("password"):
170 return apology("must provide password", 403)
171
172 # Ensure confpassword was submitted
173 elif not request.form.get("confpassword"):
174 return apology("must confirmate password", 403)
175
176 # Query database for username
177 rows = db.execute("SELECT username FROM users WHERE username = :username",
178 username=request.form.get("username"))
179
180 # Check if username is being used
181 if not rows:
182 # Insert password
183 db.execute("INSERT INTO users (username, hash) VALUES (?, ?)", request.form.get("username"), generate_password_hash(request.form.get("password")))
184 # Redirect user to home page
185 return redirect("/")
186 else:
187 return apology("username already exists", 403)
188 else:
189 return render_template("register.html")
190
191
192@app.route("/sell", methods=["GET", "POST"])
193@login_required
194def sell():
195 """Sell shares of stock"""
196 return apology("TODO")
197
198
199def errorhandler(e):
200 """Handle error"""
201 if not isinstance(e, HTTPException):
202 e = InternalServerError()
203 return apology(e.name, e.code)
204
205
206# Listen for errors
207for code in default_exceptions:
208 app.errorhandler(code)(errorhandler)