-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
232 lines (184 loc) · 9.47 KB
/
application.py
File metadata and controls
232 lines (184 loc) · 9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import os
import csv
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import apology, login_required, lookup, usd
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")
# Make sure API key is set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
@app.route("/leaderboard")
def leaderboard():
userlist=[]
sorteduserlist=[]
for i in range(len(db.execute("SELECT * FROM users"))):
userlist.append(db.execute("SELECT * FROM users")[i]['username'])
length = len(userlist)
for i in range(length):
j = i+1
if j > length:
break
user1=userlist[i]
user2=userlist[j]
user1_stock_prices_total=[]
user2_stock_prices_total=[]
user1_id=int(db.execute("SELECT id FROM users WHERE username=:username", username=user1)[0]['id'])
user2_id=int(db.execute("SELECT id FROM users WHERE username=:username", username=user2)[0]['id'])
print(db.execute("SELECT cash FROM users WHERE username = :username", username=user1))
user1_cash=db.execute("SELECT cash FROM users WHERE username = :username", username=user1)[0]['cash']
user2_cash=db.execute("SELECT cash FROM users WHERE username = :username", username=user2)[0]['cash']
user1_stocks=db.execute("SELECT * FROM stocks WHERE user_id= :user_id", user_id=user1_id)
user2_stocks=db.execute("SELECT * FROM stocks WHERE user_id= :user_id", user_id=user2_id)
for x in range(len(user1_stocks)):
user1_stock_prices_total.append(lookup(user1_stocks[x]['symbol'])['price']*user1_stocks[x]['shares'])
for y in range(len(user2_stocks)):
user2_stock_prices_total.append(lookup(user2_stocks[y]['symbol'])['price']*user2_stocks[y]['shares'])
user1_value = sum(user1_stock_prices_total)+user1_cash
user2_value = sum(user2_stock_prices_total)+user2_cash
if user2_value > user1_value:
userlist[i] = user2
userlist[j] = user1
print(userlist)
return render_template("leaderboard.html", length=length)
@app.route("/")
@login_required
def index():
user_stocks=db.execute("SELECT * FROM stocks WHERE user_id= :user_id", user_id=session["user_id"])
stock_names=[]
stock_prices=[]
stock_prices_usd=[]
stock_prices_total=[]
grand_total=0
user_cash=db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])[0]['cash']
cash_total=usd(user_cash)
length= len(user_stocks)
for i in range(length):
stock_names.append(lookup(user_stocks[i]['symbol'])['name'])
stock_prices.append(usd(lookup(user_stocks[i]['symbol'])['price']))
stock_prices_usd.append(usd(lookup(user_stocks[i]['symbol'])['price']*user_stocks[i]['shares']))
stock_prices_total.append(lookup(user_stocks[i]['symbol'])['price']*user_stocks[i]['shares'])
grand_total=usd(sum(stock_prices_total)+user_cash)
return render_template("index.html", user_stocks=user_stocks, stock_names=stock_names, length=length, stock_prices=stock_prices, stock_prices_usd=stock_prices_usd, grand_total=grand_total, cash_total=cash_total)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
if request.method == "GET":
return render_template("buy.html")
if request.method == "POST":
symbol = request.form.get("symbol")
shares = request.form.get("shares")
if symbol == "" or lookup(symbol) == None:
return apology("Please enter a valid symbol")
user_cash=db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])[0]['cash']
total_cost=float(shares)*lookup(symbol)["price"]
if user_cash < total_cost:
return apology("You can't afford to purchase those shares!")
db.execute("UPDATE users SET cash = :nettotal WHERE id = :user_id", user_id=session["user_id"], nettotal=user_cash-total_cost)
db.execute("INSERT INTO stocks (user_id, symbol, shares) VALUES(:user_id, :symbol, :shares)", user_id=session["user_id"], symbol=symbol, shares=shares)
return redirect("/")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return apology("invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
if request.method == "GET":
return render_template("quote.html")
if request.method == "POST":
stockinfo = lookup(request.form.get("symbol"))
stockinfo["price"] = usd(stockinfo["price"])
return render_template("quoted.html", stockinfo=stockinfo)
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "GET":
return render_template("register.html")
if request.method == "POST":
if not request.form.get("username") or not request.form.get("password") or not request.form.get("confirmation"):
return apology("Please complete all sections.")
if not request.form.get("password") == request.form.get("confirmation"):
return apology("Are you silly? Those passwords don't match!")
if db.execute("SELECT username FROM users WHERE username = :name LIMIT 1", name=request.form.get("username")):
return apology("That username is taken! Please choose another.")
else:
db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=(generate_password_hash(request.form.get("password"))))
return redirect("/")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
user_stocks=db.execute("SELECT * FROM stocks WHERE user_id= :user_id", user_id=session["user_id"])
length= len(user_stocks)
user_cash=db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])[0]['cash']
if request.method == "GET":
return render_template("sell.html", user_stocks=user_stocks, length=length)
if request.method == "POST":
user_shares=db.execute("SELECT shares FROM stocks WHERE user_id = :user_id AND symbol = :symbol", user_id=session["user_id"], symbol=request.form.get("symbol"))[0]["shares"]
if int(request.form.get("shares"),10) > user_shares:
return apology("You don't own that many shares!")
total_cost = int(request.form.get("shares"),10)*lookup(request.form.get("symbol"))["price"]
db.execute("UPDATE users SET cash = :nettotal WHERE id = :user_id", user_id=session["user_id"], nettotal=user_cash+total_cost)
if user_shares == int(request.form.get("shares"),10):
db.execute("DELETE FROM stocks WHERE user_id = :user_id AND symbol = :symbol", user_id=session["user_id"], symbol=request.form.get("symbol"))
if user_shares > int(request.form.get("shares"),10):
db.execute("UPDATE stocks SET shares = :netshares WHERE user_id = :user_id AND symbol = :symbol", netshares=user_shares-int(request.form.get("shares"),10), user_id=session["user_id"], symbol=request.form.get("symbol"))
return redirect("/")
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
# Listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)