· 9 years ago · Jun 27, 2017, 12:10 PM
1from cs50 import SQL
2from flask import Flask, flash, redirect, render_template, request, session, url_for
3from flask_session import Session
4from passlib.apps import custom_app_context as pwd_context
5from tempfile import mkdtemp
6import datetime
7
8from helpers import *
9
10# configure application
11app = Flask(__name__)
12
13# ensure responses aren't cached
14if app.config["DEBUG"]:
15 @app.after_request
16 def after_request(response):
17 response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
18 response.headers["Expires"] = 0
19 response.headers["Pragma"] = "no-cache"
20 return response
21
22# custom filter
23app.jinja_env.filters["usd"] = usd
24
25# configure session to use filesystem (instead of signed cookies)
26app.config["SESSION_FILE_DIR"] = mkdtemp()
27app.config["SESSION_PERMANENT"] = False
28app.config["SESSION_TYPE"] = "filesystem"
29Session(app)
30
31# configure CS50 Library to use SQLite database
32db = SQL("sqlite:///finance.db")
33
34@app.route("/")
35@login_required
36def index():
37
38 user_id = session["user_id"]
39 rows = db.execute("SELECT * FROM users WHERE id = :userid" , userid = user_id)
40 if not rows:
41 return apology("something went wrong")
42
43 users = db.execute("SELECT * FROM :username",username = rows[0]["username"])
44
45 #stocks = []
46 #for user in users:
47 # symbol = user["symbol"]
48 # item = lookup(symbol)
49 # stocks.append(str(item["price"]))
50
51 #stock = db.execute("SELECT * FROM stock ")
52
53 total_cash = float(rows[0]["cash"])
54 for row in users:
55 symbol = row["symbol"]
56 shares = row["quantity"]
57 stock = lookup(symbol)
58 total = shares * stock["price"]
59 total_cash += total
60 db.execute("UPDATE :username SET curr_price=:price, \
61 curr_val=:total WHERE symbol=:symbol", \
62 username = rows[0]["username"], \
63 price=usd(stock["price"]), \
64 total=usd(total), symbol=symbol)
65
66 #for stock in user["symbol"]:
67# print (users)
68 #print(stocks)
69
70 return render_template("index.html", total = total_cash, row = rows, users = users)
71 #return apology("TODO")
72
73@app.route("/buy", methods=["GET", "POST"])
74@login_required
75def buy():
76 """Buy shares of stock."""
77 if request.method == "POST":
78 if not request.form.get("symbol_1"):
79 return apology("pls enter correct symbol")
80 stock = lookup(request.form.get("symbol_1"))
81
82
83
84
85 if not stock:
86 return apology("something went wrong")
87 print (stock)
88
89 #rows = db.execute
90 user_id = session["user_id"]
91
92 if int(request.form.get("quantity")) < 0:
93 return apology("enter positive int")
94 new_quantity = int(request.form.get("quantity"))
95 print(new_quantity)
96
97
98 rows = db.execute("SELECT * FROM users WHERE id = :userid" , userid = user_id)
99 if not rows:
100 return apology("something went wrong")
101
102 username1 = rows[0]["username"] + '_stock'
103
104 user = db.execute("SELECT * FROM :username",username = rows[0]["username"])
105 #if not user:
106 # return apology("something went wrong")
107
108 print("check")
109 total_cost = int(request.form.get("quantity"))*stock['price']
110 print("check1")
111 # try:
112 # user_stock = db.execute("SELECT * FROM :username WHERE symbol =:symbol", username = username1, symbol = request.get.form("symbol_1")
113 #print(user_stock)
114 #except AttributeError:
115 # continue
116 print("check2")
117 # curr_quantity = int(user_stock[0]["quantity"])
118 print("check3")
119
120 if total_cost <= float(rows[0]["cash"]):
121 print("check4")
122 insert = db.execute("INSERT INTO :username (stockname, symbol, quantity, price, date) VALUES(:stockname, :symbol, :quantity, :price, :time)", \
123 username = rows[0]["username"],stockname = stock['name'], symbol= stock['symbol'], quantity = int(request.form.get("quantity")), price = stock['price'] , time = str(datetime.datetime.now()))
124 print("check5")
125 if not insert:
126 return apology("something went wrong")
127
128 update = db.execute("UPDATE users SET cash = :cash WHERE username = :username", cash = float(rows[0]["cash"]) - total_cost, username = rows[0]["username"])
129 print("check6")
130 if not update:
131 return apology("something went wrong")
132
133 #username = request.form.get("username") + '_stock'
134 print("check7")
135 #hey = db.execute("SELECT * FROM :username WHERE symbol = :symbol", username = username1, symbol = request.form.get("symbol_1"))
136 #if not hey:
137 update_stock = db.execute("INSERT OR REPLACE INTO :username (stockname, symbol, quantity) VALUES (:stockname, :symbol, quantity +:new_quantity)",\
138 username = username1, \
139 stockname = stock['name'],\
140 symbol = request.form.get("symbol_1"),\
141 new_quantity = int(new_quantity))
142 #else:
143 # update_stock = db.execute("UPDATE :username SET quantity = quantity +:new_quantity WHERE symbol = :symbol",\
144 # username = username1, \
145 # new_quantity = int(request.form.get("quantity")), \
146 # symbol = request.get.form("symbol_1") )
147 print("check8")
148 if not update_stock:
149 return apology("something went wrong")
150
151 return redirect(url_for('index'))
152
153 else:
154 return render_template("buy.html")
155 #return apology("TODO")
156
157@app.route("/history")
158@login_required
159def history():
160 """Show history of transactions."""
161 return apology("TODO")
162
163@app.route("/login", methods=["GET", "POST"])
164def login():
165 """Log user in."""
166
167 # forget any user_id
168 session.clear()
169
170 # if user reached route via POST (as by submitting a form via POST)
171 if request.method == "POST":
172
173 # ensure username was submitted
174 if not request.form.get("username"):
175 return apology("must provide username")
176
177 # ensure password was submitted
178 elif not request.form.get("password"):
179 return apology("must provide password")
180
181 # query database for username
182 rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
183
184 # ensure username exists and password is correct
185 if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
186 return apology("invalid username and/or password")
187
188 # remember which user has logged in
189 session["user_id"] = rows[0]["id"]
190
191 # redirect user to home page
192 return redirect(url_for("index"))
193
194 # else if user reached route via GET (as by clicking a link or via redirect)
195 else:
196 return render_template("login.html")
197
198@app.route("/logout")
199def logout():
200 """Log user out."""
201
202 # forget any user_id
203 session.clear()
204
205 # redirect user to login form
206 return redirect(url_for("login"))
207
208@app.route("/quote", methods=["GET", "POST"])
209@login_required
210def quote():
211 """Get stock quote."""
212 if request.method == "POST":
213 #if not request.form.get("symbol_1"):
214 # return apology("pls enter correct symbol")
215
216 rows = lookup(request.form.get("symbol_1"))
217 if not rows:
218 return apology("something went wrong")
219
220 #rows.price = usd(rows.price)
221
222 return render_template("quoted.html",stock = rows)
223 else:
224 return render_template("quote.html")
225
226
227
228@app.route("/register", methods=["GET", "POST"])
229def register():
230 """Register user."""
231
232 session.clear()
233
234 if request.method == "POST":
235 if not request.form.get("username"):
236 return apology("must provide username")
237
238 # ensure password was submitted
239 if not request.form.get("password"):
240 return apology("must provide password")
241
242 # password is not mis-typed first time
243 if request.form.get("password") != request.form.get("re_password"):
244 return apology("passwords do not match")
245
246 #hashing the password
247 password = request.form.get("password")
248 hash = pwd_context.hash(password)
249
250
251
252 result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
253 #result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username='cj', hash='dsff')
254 if not result:
255 return apology("username already exists!")
256
257
258
259 create = db.execute("CREATE TABLE :username ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'stockname' TEXT NOT NULL, 'symbol' TEXT NOT NULL, 'quantity' NUMERIC NOT NULL DEFAULT 0, 'price' NUMERIC NOT NULL DEFAULT 0.0 , 'date' TIMESTAMP NOT NULL, 'curr_price' NUMERIC, 'curr_val' NUMERIC)",username = request.form.get("username"))
260 username = request.form.get("username") + '_stock'
261 create1 = db.execute("CREATE TABLE :username ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'stockname' TEXT NOT NULL, 'symbol' TEXT NOT NULL, 'quantity' NUMERIC NOT NULL DEFAULT 0)",username = username)
262
263 if not create:
264 return apology("something went wrong")
265 if not create1:
266 return apology("something went wrong")
267
268 rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
269 if not rows:
270 return apology("something went wrong")
271 session["user_id"] = rows[0]["id"]
272 return redirect(url_for('index'))
273 else:
274 return render_template("register.html")
275
276
277
278@app.route("/sell", methods=["GET", "POST"])
279@login_required
280def sell():
281 """Sell shares of stock."""
282 if request.method == 'POST':
283 if not request.form.get("symbol_1"):
284 return apology("pls enter correct symbol")
285 stock = lookup(request.form.get("symbol_1"))
286 if not stock:
287 return apology("something went wrong")
288 print (stock)
289
290 #rows = db.execute
291 user_id = session["user_id"]
292
293 if int(request.form.get("quantity")) < 0:
294 return apology("enter positive int")
295
296
297 rows = db.execute("SELECT * FROM users WHERE id = :userid" , userid = user_id)
298 if not rows:
299 return apology("something went wrong")
300
301 user = db.execute("SELECT * FROM :username",username = rows[0]["username"])
302 if not user:
303 return apology("something went wrong")
304
305 total_cost = int(request.form.get("quantity"))*stock['price']
306
307 new_total = float(rows[0]["cash"]) + total_cash
308
309 current_stock_quantity = db.execute("SELECT * FROM :username WHERE symbol = :symbol", symbol = request.form.get("symbol_1"))
310 if not current_stock_quantity:
311 return apology("something went wrong")
312
313 new_quantity = int(current_stock_quantity[0]) - int(request.form.get("quantity"))
314 if new_quantity >= 0:
315 current = db.execute("INSERT INTO :username (stockname, symbol, quantity, price, date) VALUES(:stockname, :symbol, :quantity, :price, :time)", \
316 username = rows[0]["username"],stockname = stock['name'], symbol= stock['symbol'], quantity = -int(request.form.get("quantity")), price = stock['price'] , time = str(datetime.datetime.now()))
317
318 if not insert:
319 return apology("something went wrong")
320
321 update = db.execute("UPDATE users SET cash = :cash WHERE username = :username", cash = float(rows[0]["cash"]) - total_cost, username = rows[0]["username"])
322 if not update:
323 return apology("something went wrong")
324
325
326
327 return redirect(url_for('index'))
328
329 else:
330 return render_template("sell.html")