-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsgi.py
273 lines (232 loc) · 9.32 KB
/
wsgi.py
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
import os
from flask import Flask, render_template, session, redirect, request, url_for, jsonify
# from flaskext.mysql import MySQL
import traceback
import logging
import mysql.connector
from utils.recommendations import Recommendation
__author__ = 'hanvitha'
app = Flask(__name__)
app.static_folder = 'static'
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_Blah"gd5HK\n\xec]/'
app.logger.setLevel(logging.DEBUG)
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
APP_ROOT = os.getenv('APP_ROOT')
# DB connection details
# host = "localhost"
# port = '3306'
# user = "root"
# password = "rootpass"
# database = "ms"
database = os.getenv('dbname')
user = os.getenv('dbusername')
password = os.getenv('dbpassword')
host = os.getenv('MYSQL_SERVICE_HOST')
port = os.getenv('MYSQL_SERVICE_PORT')
@app.route("/")
def index(error=None):
if 'userid' in session:
return redirect(url_for('home'))
else:
session.clear()
return render_template("index.html", error=error)
@app.route("/login", methods=["POST"])
def login():
email = request.form['login_user']
password = request.form['login_password']
# db, cursor = connectToDB()
try:
userquery = f"select id, name from users where email='{email}' and password='{password}';"
cursor.execute(userquery)
if cursor.rowcount > 0:
userrecord = cursor.fetchone()
session['userid'] = userrecord[0]
session['email'] = email
session['name'] = userrecord[1]
print("session variables done!" + str(session['userid']) + " " + str(session['name']))
return redirect(url_for('home'))
else:
return render_template("index.html", error="Invalid credentials")
except Exception as e:
logging.exception("Login error")
@app.route("/home", methods=["GET"])
def home():
try:
print("Session is " + session['name'])
if 'userid' in session:
print("Welcome home babe")
trending = []
message = "Welcome " + session['name']
similarMovies = None
try:
trending = recommObject.getTrendingRecommendations()
if 'latestmovie' in session:
latestmovie = session['latestmovie']
print(latestmovie)
# moviequery = f"select title from movies where id='{latestmovie}';"
# cursor.execute(moviequery)
# if cursor.rowcount >0:
# movierec = cursor.fetchone()
# moviename = movierec[0]
similarMovies = recommObject.getContentBasedRecomm(latestmovie).head(15)
# similarMovies = pd.DataFrame({'movieid':simMoviesSeries.index, 'title':simMoviesSeries.values})
# similarMovies = simMoviesSeries.to_frame().rename(columns={0:'id'})
print(similarMovies.head(10))
similarMovies = similarMovies.values.tolist()
print(similarMovies)
except Exception as e:
traceback.print_exc()
finally:
return render_template("home.html", trending=trending, similarMovies=similarMovies, message=message)
else:
return render_template("index.html", error="Login Required to access the website")
except Exception as e:
traceback.print_exc()
logging.exception("Home page error")
@app.route("/signup", methods=["POST"])
def signup():
try:
name = request.form['signup_name']
password = request.form['signup_password']
email = request.form['signup_email']
zipcode = request.form['signup_zipcode']
age = request.form['signup_age']
# db, cursor = connectToDB()
userquery = f"select id from users where email='{email}';"
cursor.execute(userquery)
if cursor.rowcount > 0:
return render_template("index.html", error="Email ID already in use!")
userquery = f"insert into users (id, password, name, email, zipcode, age) values (default, '{password}','{name}', '{email}', '{zipcode}', '{age}');"
cursor.execute(userquery)
db.commit()
try:
userquery = f"select id from users where email='{email}';"
cursor.execute(userquery)
if cursor.rowcount > 0:
session["userid"] = cursor.fetchone()[0]
session["email"] = email
session["name"] = name
return redirect(url_for("home"))
except Exception as e:
logging.exception("Signing in after signup error")
except Exception as e:
traceback.print_exc()
logging.exception("Signup error external")
def connectToDB():
db = mysql.connector.connect(host=host,
user=user,
password=password,
database=database,
port=port
)
cursor = db.cursor(buffered=True)
return db, cursor
@app.route('/profile')
def profile():
if 'userid' not in session:
return render_template("index.html", error="Login required to access website!")
return render_template('profile.html', name=session['name'], email=session['email'])
@app.route('/movie', methods=["GET"])
def movie():
if 'userid' not in session:
return render_template("index.html", error="Login required to access website!")
try:
movieid = request.args.get('id')
print("ID is" + movieid)
db, cursor = connectToDB()
cursor.execute(f"select * from movies where id='{movieid}';")
movieRecord = cursor.fetchone()
# print(movieRecord)
if (not movieRecord):
redirect(url_for('home'))
moviename = movieRecord[1]
year = movieRecord[2]
overview = movieRecord[4]
cursor.execute(f"select genreid from movie_genres where movieid='{movieid}';")
genreid = cursor.fetchone()
genres = []
while genreid is not None:
# print(genreid)
cursor.execute(f"select name from genres where id='{genreid[0]}';")
genre = cursor.fetchone()[0]
# print(genre)
genres.append(genre)
genreid = cursor.fetchone()
cursor.execute(f"select count(*) from ratings where movieid='{movieid}';")
count = cursor.fetchone()[0]
cursor.execute(f"select ROUND(AVG(rating), 1) from ratings where movieid='{movieid}';")
rating = cursor.fetchone()[0]
if (not rating):
rating = 0
count = 1
# print(rating)
return render_template('movie.html', movie=moviename, movieid=movieid, year=year, genres=genres, count=count, rating=rating, overview=overview)
except Exception as e:
traceback.print_exc()
logging.exception("Movie page error")
@app.route('/watchmovie', methods=["POST","GET"])
def watchmovie():
if 'userid' not in session:
return render_template("index.html", error="Login required to access website!")
else:
if request.method=="POST":
movie = request.form['movie']
else:
movie = request.args.get('movie')
session['latestmovie'] = movie
return render_template('watchmovie.html')
@app.route('/watchbygenre', methods=['GET'])
def watchbygenre():
if 'userid' not in session:
return render_template("index.html", error="Login required to access website!")
else:
try:
genreid = request.args.get('genre')
cursor.execute(f"select name from genres where id={genreid}")
genreName = cursor.fetchone()[0]
print('Watching by genre '+genreName)
movies = recommObject.getMoviesByGenre(genreid, cursor)
# print(movies)
return render_template('genres.html', genreName=genreName, moviesByGenre=movies)
except Exception as e:
traceback.print_exc()
return render_template('genres.html',genreName=None, moviesByGenre=None)
@app.route('/submitrating', methods=["POST"])
def submitrating():
try:
rating = request.form['rating']
movieid = request.form['movieid']
print(rating)
print(movieid)
query = "insert into ratings (id, userid, movieid, rating) values (default, %s,%s,%s );"
print(query, (session['userid'], movieid, rating))
cursor.execute(query, (session['userid'], movieid, rating))
db.commit()
return jsonify({'response': 'submitted response'})
except:
traceback.print_exc()
return jsonify({'oops! something went wrong. Try again!'})
@app.route('/logout')
def logout():
session.pop('userid', None)
session.pop('name', None)
session.pop('email', None)
session.pop('latestmovie ', None)
session.clear()
return redirect(url_for('index'))
db, cursor = connectToDB()
# w2b = WriteToDbObj(db,cursor)
# w2b.writeUsers()
# w2b.writeRatings()
# w2b.writeMovies()
# w2b.writeGenres()
# w2b.writeMovieGenres()
recommObject = Recommendation(db)
print("Preparing content based recom")
recommObject.prepareContentBasedRecomm()
print("Done preparing recomm")
if __name__ == '__main__':
logout()
print("Running app!Praise God")
app.run(debug=True)