· 6 years ago · Dec 29, 2019, 06:46 AM
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("/")
44@login_required
45def index():
46 """Show portfolio of stocks"""
47 return apology("TODO")
48
49
50@app.route("/buy", methods=["GET", "POST"])
51@login_required
52def buy():
53 """Buy shares of stock"""
54 return apology("TODO")
55
56
57@app.route("/check", methods=["GET"])
58def check():
59 """Return true if username available, else false, in JSON format"""
60 return jsonify("TODO")
61
62
63@app.route("/history")
64@login_required
65def history():
66 """Show history of transactions"""
67 return apology("TODO")
68
69
70@app.route("/login", methods=["GET", "POST"])
71def login():
72 """Log user in"""
73
74 # Forget any user_id
75 session.clear()
76
77 # User reached route via POST (as by submitting a form via POST)
78 if request.method == "POST":
79
80 # Ensure username was submitted
81 if not request.form.get("username"):
82 return apology("must provide username", 403)
83
84 # Ensure password was submitted
85 elif not request.form.get("password"):
86 return apology("must provide password", 403)
87
88 # Query database for username
89 rows = db.execute("SELECT * FROM users WHERE username = :username",
90 username=request.form.get("username"))
91
92 # Ensure username exists and password is correct
93 if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
94 return apology("invalid username and/or password", 403)
95
96 # Remember which user has logged in
97 session["user_id"] = rows[0]["id"]
98
99 # Redirect user to home page
100 return redirect("/")
101
102 # User reached route via GET (as by clicking a link or via redirect)
103 else:
104 return render_template("login.html")
105
106
107@app.route("/logout")
108def logout():
109 """Log user out"""
110
111 # Forget any user_id
112 session.clear()
113
114 # Redirect user to login form
115 return redirect("/")
116
117
118@app.route("/quote", methods=["GET", "POST"])
119@login_required
120def quote():
121 """Get stock quote."""
122 return apology("TODO")
123
124
125@app.route("/register", methods=["GET", "POST"])
126def register():
127 """Register user"""
128 # forget any user_id
129 session.clear()
130
131 #user reached route via post
132 if request.method == "POST":
133
134 # getting the username password and confirmation
135 username = request.form.get("username")
136 password = request.form.get("password")
137 confirmation = request.form.get("confirmation")
138
139 #selecting rows from user
140 rows = db.execute("SELECT * FROM users WHERE username = :username", username = request.form.get("username"))
141
142 # if not len(rows):
143 # return apology("Username already taken")
144
145 #Check if username field is kept blank and already taken
146
147 if username == "":
148 return apology ("Please enter the username")
149 elif len(rows) == 1:
150 return apology("username already taken")
151
152 #check for password and confirmation
153 if password == "":
154 return apology("you need to enter the password")
155 elif password != confirmation:
156 return apology ("entered password do not matches")
157
158 hashed = generate_password_hash(password)
159
160 #adding to the database
161 results = db.execute("INSERT INTO users(username, hash) VALUES(:username, :password)", username = username, password = hashed)
162
163 session["user_id"] = results["id"]
164
165 #redirect user to homepage
166 return redirect("/login")
167
168 else:
169 return render_template("register.html")
170
171
172 return apology("TODO")
173
174
175@app.route("/sell", methods=["GET", "POST"])
176@login_required
177def sell():
178 """Sell shares of stock"""
179 return apology("TODO")
180
181
182def errorhandler(e):
183 """Handle error"""
184 if not isinstance(e, HTTPException):
185 e = InternalServerError()
186 return apology(e.name, e.code)
187
188
189# Listen for errors
190for code in default_exceptions:
191 app.errorhandler(code)(errorhandler)