-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
279 lines (191 loc) · 7.29 KB
/
Copy pathapplication.py
File metadata and controls
279 lines (191 loc) · 7.29 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import os, json
from flask import (
Flask,
session,
redirect,
render_template,
request,
jsonify,
url_for,
flash,
)
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from werkzeug.security import check_password_hash, generate_password_hash
import requests
from helpers import login_required
app = Flask(__name__)
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
@app.route("/")
@login_required
def index():
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
session.clear()
username = request.form.get("username")
if request.method == "POST":
if not request.form.get("username"):
return render_template("error.html", message="must provide username")
elif not request.form.get("password"):
return render_template("error.html", message="must provide password")
rows = db.execute(
"SELECT * FROM users WHERE username = :username", {"username": username}
)
result = rows.fetchone()
if result == None or not check_password_hash(
result[2], request.form.get("password")
):
return render_template(
"error.html", message="invalid username and/or password"
)
session["user_id"] = result[0]
session["user_name"] = result[1]
return redirect("/")
else:
return render_template("login.html")
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
@app.route("/register", methods=["GET", "POST"])
def register():
session.clear()
if request.method == "POST":
if not request.form.get("username"):
return render_template("error.html", message="must provide username")
userCheck = db.execute(
"SELECT * FROM users WHERE username = :username",
{"username": request.form.get("username")},
).fetchone()
print('>>>>', userCheck)
if userCheck:
return render_template("error.html", message="username already exist")
elif not request.form.get("password"):
return render_template("error.html", message="must provide password")
elif not request.form.get("confirmation"):
return render_template("error.html", message="must confirm password")
elif not request.form.get("password") == request.form.get("confirmation"):
return render_template("error.html", message="passwords didn't match")
hashedPassword = generate_password_hash(
request.form.get("password"), method="pbkdf2:sha256", salt_length=8
)
db.execute(
"INSERT INTO users (username, password) VALUES (:username, :password)",
{"username": request.form.get("username"), "password": hashedPassword},
)
session["username"] = request.form.get("username")
db.commit()
flash("Account created", "info")
return redirect("/login")
else:
return render_template("register.html")
@app.route("/search", methods=["GET"])
@login_required
def search():
if not request.args.get("book"):
return render_template("error.html", message="you must provide a book.")
query = "%" + request.args.get("book") + "%"
query = query.title()
rows = db.execute(
"SELECT isbn, title, author, year FROM books WHERE \
isbn LIKE :query OR \
title LIKE :query OR \
author LIKE :query LIMIT 15",
{"query": query},
)
if rows.rowcount == 0:
return render_template(
"error.html", message="we can't find books with that description."
)
books = rows.fetchall()
return render_template("results.html", books=books)
@app.route("/book/<isbn>", methods=["GET", "POST"])
@login_required
def book(isbn):
""" Save user review and load same page with reviews updated."""
if request.method == "POST":
currentUser = session["user_id"]
rating = request.form.get("rating")
comment = request.form.get("comment")
row = db.execute("SELECT id FROM books WHERE isbn = :isbn", {"isbn": isbn})
bookId = row.fetchone()
bookId = bookId[0]
row2 = db.execute(
"SELECT * FROM reviews WHERE user_id = :user_id AND book_id = :book_id",
{"user_id": currentUser, "book_id": bookId},
)
if row2.rowcount == 1:
flash("You already submitted a review for this book", "warning")
return redirect("/book/" + isbn)
rating = int(rating)
db.execute(
"INSERT INTO reviews (user_id, book_id, comment, rating) VALUES \
(:user_id, :book_id, :comment, :rating)",
{
"user_id": currentUser,
"book_id": bookId,
"comment": comment,
"rating": rating,
},
)
db.commit()
flash("Review submitted!", "info")
return redirect("/book/" + isbn)
else:
row = db.execute(
"SELECT isbn, title, author, year FROM books WHERE \
isbn = :isbn",
{"isbn": isbn},
)
bookInfo = row.fetchall()
key = os.getenv("GOODREADS_KEY")
query = requests.get(
"https://www.goodreads.com/book/review_counts.json",
params={"key": key, "isbns": isbn},
)
response = query.json()
response = response["books"][0]
bookInfo.append(response)
row = db.execute("SELECT id FROM books WHERE isbn = :isbn", {"isbn": isbn})
book = row.fetchone()
book = book[0]
results = db.execute(
"SELECT users.username, comment, rating, \
to_char(time, 'DD Mon YY - HH24:MI:SS') as time \
FROM users \
INNER JOIN reviews \
ON users.id = reviews.user_id \
WHERE book_id = :book \
ORDER BY time",
{"book": book},
)
reviews = results.fetchall()
return render_template("book.html", bookInfo=bookInfo, reviews=reviews)
@app.route("/api/<isbn>", methods=["GET"])
@login_required
def api_call(isbn):
row = db.execute(
"SELECT title, author, year, isbn, \
COUNT(reviews.id) as review_count, \
AVG(reviews.rating) as average_score \
FROM books \
INNER JOIN reviews \
ON books.id = reviews.book_id \
WHERE isbn = :isbn \
GROUP BY title, author, year, isbn",
{"isbn": isbn},
)
if row.rowcount != 1:
return jsonify({"Error": "Invalid book ISBN"}), 422
tmp = row.fetchone()
result = dict(tmp.items())
result["average_score"] = float("%.2f" % (result["average_score"]))
return jsonify(result)