-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.py
428 lines (358 loc) · 18.7 KB
/
routes.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from flask import Flask, render_template, request, jsonify, url_for, redirect, make_response, session
from flask.ext.login import LoginManager, UserMixin, login_required, login_user
from class_search_web_scrapping import GetCoursesTaught,GetAllProfessors, GetOptions, Sort_dict, GetClasses, GetSubjectsInDepartments, GetClassDescriptionAndAll, GetAllProfessorDepartments
from database_functions import easiestClass, bestClass, easiestProf,bestProf,getClassReviews, getProfReviews, addClassReview, addProfReview, calculateProfRatings, calculateClassRatings
from password import create_user, validate_user
import requests
from User import User
app = Flask(__name__)
app.secret_key = 'some_secret'
login_manager = LoginManager()
login_manager.init_app(app)
Options = GetOptions()
Professors = GetAllProfessors()
ProfDepartments = GetAllProfessorDepartments()
def is_logged_in(id):
user = load_User(id)
if user != None:
if user.authenticated == True:
return True
return False
def load_User(id):
return User.get(id)
def logout():
session['username'] = None
return
def GetCurrentSemester():
return '201520'
@app.route('/register', methods = ["GET", "POST"])
def register():
error = None
if request.method == "POST":
if request.form["password"] != request.form["password confirmation"]:
error = "Passwords did not match"
return render_template('UserRegistration.html', error = error)
Response, Message = create_user(request.form["username"], request.form["password"])
if not Response:
error = Message
else:
return redirect(url_for('home'))
return render_template('UserRegistration.html', error = error)
@app.route('/login', methods = ["GET", "POST"])
def login():
error = None
if request.method == "POST":
if request.form.get("RememberMe"):
pass
### Call function that remembers user
else:
pass
### call function that sets timelimit on user
Response, Message = validate_user(request.form["username"], request.form["password"])
if not Response:
error = Message
else:
user = load_User(request.form["username"])
session['username'] = user.id
return redirect(url_for('home'))
return render_template('login.html', error=error)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/class_search/quick-search=<ATTR>', methods = ["POST", "GET"])
def QuickSearch(ATTR):
if request.method == "POST":
Term = request.form['TermOptions']
Subject = request.form.getlist('SubjectOptions')
Credit = request.form['CreditsOptions']
Attribute = request.form['AttributeOptions']
Division = request.form['DivisionOptions']
Campus = request.form['CampusOptions']
return DisplayClasses(Term, Subject, Credit, Attribute, Division, Campus)
Attributes = {'2nd Theology':'THE2', '2nd Philosophy':'PHI2', 'Social Science': 'SOSC', 'Natural Science (req)': 'NASC', 'Fine Arts':'FNAR', 'Literature':'LIT', 'History': 'HIST', "University Seminar":"USEM", "Sophomore Business Courses":"BA02", "Junior Business Courses": "BA03"}
Subjects = Options[3].values()
Semester = GetCurrentSemester()
Attribute = Attributes[ATTR]
return DisplayClasses(Semester, Subjects, Options[5]["All"],Attribute,"A", Options[2]["Main"])
@app.route('/search/<query>/', methods = ['POST'])
def Search(query):
unicode_profs = {}
for prof in Professors:
prof_name = unicode(prof, "utf-8")
if query.lower() in prof_name.lower():
unicode_profs[prof_name] = '/instructor_info/' + prof_name
return jsonify(unicode_profs)
@app.route('/class_search/', methods = ['GET', 'POST'])
def ClassSearch():
if request.method == 'POST':
Term = request.form['TermOptions']
Subject = request.form.getlist('SubjectOptions')
Credit = request.form['CreditsOptions']
Attribute = request.form['AttributeOptions']
Division = request.form['DivisionOptions']
Campus = request.form['CampusOptions']
return DisplayClasses(Term, Subject, Credit, Attribute, Division, Campus)
return render_template('class_search.html', TermOptionKeys = Sort_dict(Options[0], True), TermOptions = Options[0] ,
DivisionOptionKeys = Sort_dict(Options[1], False), DivisionOptions = Options[1],
CampusOptionKeys = Sort_dict(Options[2], False), CampusOptions = Options[2],
SubjectOptionKeys = Sort_dict(Options[3], False), SubjectOptions = Options[3],
AttributeOptionKeys = Sort_dict(Options[4], False), AttributeOptions = Options[4],
CreditsOptionKeys = Sort_dict(Options[5], False), CreditsOptions = Options[5] )
# @app.route('/class_search/<class_info>/')
# def classInfo(class_info):
# CourseRatings = calculateClassRatings(getClassReviews('', class_info))
# Course_text_review = str(CourseRatings[3])
# toughness = str(CourseRatings[4])
# interest = str(CourseRatings[5])
# Textbook = str(CourseRatings[6])
# return render_template('class_info.html', Textbook = Textbook, interest = interest,toughness = toughness,Course_text_review = Course_text_review )
@app.route('/instructor_eval/')
def eval():
return render_template('instructor_eval.html', DepartmentKeys= Sort_dict(GetOptions()[3], False), DepartmentOptions = GetOptions()[3])
@app.route('/class_search/')
def DisplayClasses(term, subject, credit, attr, divs, campus):
global Professors
global ProfDepartments
ClassList = GetClasses(term, subject, credit, attr, divs, campus)
didAddProf = False
didAddDept = False
# Checks to see if every instructor is is Professors dictionary. If they
# are not, we add their names to the text file, and recalculate the Professors dictionary
ProfsAdded = []
for course in ClassList:
try:
profs = course['Instructor']
Department = ''.join([char for char in course['Course - Sec'].split(' ')[0] if char.isalpha()])
P = [course['Teacher_Info'][i].split('P=')[-1] for i in range(len(course['Teacher_Info']))]
for i in range(len(profs)):
if profs[i] not in Professors:
f = open('TeacherList.txt', 'a')
f.write('<OPTION VALUE="' + str(P[i]) + '">' + str(profs[i]) + '\n')
f.close()
didAddProf = True
if profs[i] not in ProfDepartments and (profs[i], Department) not in ProfsAdded :
f = open('ProfessorDepartments.txt', 'a')
f.write(str(profs[i]) + '; Departments:'+ Department + '\n')
f.close()
didAddDept = True
ProfsAdded.append((profs[i], Department))
if Department not in ProfDepartments[profs[i]] and (profs[i], Department) not in ProfsAdded:
f = open('ProfessorDepartments.txt', 'a')
f.write(str(profs[i]) + '; Departments:'+ Department + '\n')
f.close()
didAddDept = True
ProfsAdded.append((profs[i], Department))
except KeyError:
pass
if didAddProf:
Professors = GetAllProfessors()
didAddProf = False
if didAddDept:
ProfDepartments = GetAllProfessorDepartments()
didAddDept = False
# Keys specifies what exactly we want to show up on our class search
Keys = ['Title', 'Course - Sec','View_Books', 'Cr', 'Max', 'Opn', 'CRN','Teacher_Info', 'Instructor', 'When','Begin','End','Where']
return render_template('DisplayClassData.html', TermOptionKeys = Sort_dict(Options[0], True), TermOptions = Options[0] ,
DivisionOptionKeys = Sort_dict(Options[1], False), DivisionOptions = Options[1],
CampusOptionKeys = Sort_dict(Options[2], False), CampusOptions = Options[2],
SubjectOptionKeys = Sort_dict(Options[3], False), SubjectOptions = Options[3],
AttributeOptionKeys = Sort_dict(Options[4], False), AttributeOptions = Options[4],
CreditsOptionKeys = Sort_dict(Options[5], False), CreditsOptions = Options[5], ClassList = ClassList, Keys = Keys)
@app.route('/class_info/<Class>-<CRN>-<Term>')
def DisplayClassPage(Class, CRN, Term):
CourseName = Class
Descriptions = GetClassDescriptionAndAll(CRN, Term)
CourseDescription = Descriptions[0]
Reviews = getClassReviews('', Class)
CourseRatings = calculateClassRatings(Reviews)
CourseTextReviews = [review[3] for review in Reviews [0] if review[3] != '']
toughness = CourseRatings[3]
interest = CourseRatings[4]
Textbook = CourseRatings[5]
if type(toughness) == str:
Overall_Rating = ''
else:
Overall_Rating = round((toughness + interest) / 2.0, 2)
# Round numbers
if type(toughness) == float:
toughness = round(toughness,2)
if type(interest) == float:
interest = round(interest,2)
if type(Textbook) == float:
Textbook = round(Textbook,2)
Prerequisites = ''
Corequisites = ''
if Descriptions[1] == "Corequisite Only":
Corequisites = Descriptions[2]
Attributes = Descriptions[3]
Restrictions = Descriptions[4]
Registration = Descriptions[5]
CrossListed = Descriptions[6]
elif Descriptions[1] == "Both":
Prerequisites = Descriptions[2]
Corequisites = Descriptions[3]
Attributes = Descriptions[4]
Restrictions = Descriptions[5]
Registration = Descriptions[6]
CrossListed = Descriptions[7]
elif Descriptions[1] == 'Prerequisite Only':
Prerequisites = Descriptions[2]
Attributes = Descriptions[3]
Restrictions = Descriptions[4]
Registration = Descriptions[5]
CrossListed = Descriptions[6]
else:
Attributes = Descriptions[2]
Restrictions = Descriptions[3]
Registration = Descriptions[4]
CrossListed = Descriptions[5]
Restrictions = ["Must " + i for i in Restrictions.split("Must")[1:]]
Remaining = Registration.split("TOTAL")[1]
Remaining = Remaining.split("\n")[1:-1]
# Spots = []
# if CrossListed:
# CrossListed = CrossListed.split("\n\n\n")[1:-1]
# temp = []
# for i in CrossListed:
# data = i.split("\n")
# Spots.append(data[2:])
# courseName = data[0]
return render_template('class_info.html',CourseTextReviews = CourseTextReviews,CrossListed = CrossListed ,Registration = Remaining, Restrictions = Restrictions, Overall_Rating = Overall_Rating,Prerequisites = Prerequisites, Corequisites = Corequisites, CourseName = CourseName, CourseDescription = CourseDescription, Textbook = Textbook, interest = interest,toughness = toughness, Attributes = Attributes )
@app.route('/DepartmentsMain/')
def DepartmentsMainPage():
DepartmentsByCollege = GetSubjectsInDepartments()
Colleges = [ 'College of Arts & Letters', 'College of Engineering', 'College of Science','Mendoza College of Business','First Year of Studies', 'The Law School', "St. Mary's College",'Other','School of Architecture']
return render_template('DepartmentsMain.html', DepartmentsByCollege = DepartmentsByCollege, Colleges = Colleges)
@app.route('/InstructorByCollege/<College>')
def InstructorByCollege(College):
Departments = [i for i in GetSubjectsInDepartments() if College in i[0]][0][1:]
return render_template('InstructorByCollege.html', College = College ,Departments = Departments, Teachers = Teachers)
@app.route('/Department/<Department>')
def InstructorByDepartment(Department):
# Place holder lists
#Teachers = set([''.join([i[0], i[1]]) for i in getProfReviews('', '',Options[3][Department], '')])
Teachers = sorted([prof for prof in ProfDepartments if Options[3][Department] in ProfDepartments[prof]])
Teachers_Sorted = Sort_dict(Teachers, False)
Best_Professors = bestProf(Options[3][Department])
Best_Teachers,Best_Teachers_Sorted = bestProf(Options[3][Department])#Best_Professors[0], Best_Professors[1]
Easiest_Teachers,Easiest_Teachers_Sorted = easiestProf(Options[3][Department])
Best_Classes,Best_Classes_Sorted = bestClass(Options[3][Department])
Crn_and_Term = {}
for course in Best_Classes_Sorted:
Course = getClassReviews('', course)[0][0]
Crn_and_Term[Course[2]] = ((Course[-2], Course[-1]))
Easiest_Classes,Easiest_Classes_Sorted = easiestClass(Options[3][Department])
DepartmentOptions = Options[3]
for option in DepartmentOptions:
if DepartmentOptions[option] == Department:
Department = option
return render_template('Department.html',Teachers_Sorted = Teachers_Sorted,Best_Teachers_Sorted = Best_Teachers_Sorted,Best_Teachers = Best_Teachers,
Easiest_Teachers = Easiest_Teachers,Easiest_Teachers_Sorted = Easiest_Teachers_Sorted, Department = Department,Teachers = Teachers,
Best_Classes = Best_Classes,Best_Classes_Sorted = Best_Classes_Sorted,Easiest_Classes = Easiest_Classes, Easiest_Classes_Sorted = Easiest_Classes_Sorted
,Crn_and_Term = Crn_and_Term)
@app.route('/instructor_info/<ProfessorName>')
def Instructor(ProfessorName):
try:
CoursesTaught = GetCoursesTaught(Professors[ProfessorName])
num_items = len(CoursesTaught[0]) - 1 # need this to be index of semester code
except KeyError:
CoursesTaught = []
RevisedCoursesTaught = []
for i in xrange(len(CoursesTaught)):
if i != 0:
if (CoursesTaught[i][0].split()[0] != CoursesTaught[i-1][0].split()[0]) or (CoursesTaught[i][num_items] != CoursesTaught[i-1][num_items]):
RevisedCoursesTaught.append(CoursesTaught[i])
else:
RevisedCoursesTaught.append(CoursesTaught[i])
last_name = str(ProfessorName.split(',')[0]) + ','
first_name = str(ProfessorName.split(',')[1])
Reviews = getProfReviews(Professors[last_name + first_name])
OverallRatings = calculateProfRatings(Reviews)
ProfessorDescriptions = [review[2] for review in Reviews]
ReviewCount = len(Reviews)
workload = OverallRatings[3]
if type(workload) == float:
workload = round(workload,2)
grading = OverallRatings[4]
if type(grading) == float:
grading = round(grading,2)
quality = OverallRatings[5]
if type(quality) == float:
quality = round(quality, 2)
accessibility = OverallRatings[6]
if type(accessibility) == float:
accessibility = round(accessibility,2)
syllabus = OverallRatings[7]
if type(syllabus) == float:
accessibility = round(accessibility,2)
ProfReviews = OverallRatings[2]
return render_template('instructor_info.html',Courses = RevisedCoursesTaught,ProfessorDescriptions = ProfessorDescriptions, ProfessorName = ProfessorName ,ProfReviews = ProfReviews, workload = workload,grading = grading, quality = quality, accessibility = accessibility, ReviewCount = ReviewCount)
@app.route('/BestClassesFor/', methods = ['GET', 'POST'])
def BestClassesFor(page = 1):
# Dummy list until we can access classes from database
if page == 1:
Attributes = {'2nd Theology':'THE2', '2nd Philosophy':'PHI2', 'Social Science': 'SOSC', 'Natural Science (req)': 'NASC'}
elif page == 2:
Attributes = {'Fine Arts':'FNAR', 'Literature':'LIT', 'History': 'HIST'}
ClassList = []
if page == 1:
SubjectsSorted = ['2nd Theology', '2nd Philosophy', 'Social Science', 'Natural Science (req)']
elif page == 2:
SubjectsSorted = ['Fine Arts', 'Literature', 'History']
Indexs = range(len(SubjectsSorted))
for attr in SubjectsSorted:
courses = GetClasses('201510', Options[3].values(), 'A', Attributes[attr],'A', 'M')
course_container = []
for i in courses:
course_container.append([i['Title'], i['CRN'], i['Term']])
ClassList.append(course_container)
return render_template('BestClassesFor.html', Subjects = Attributes, SubjectsSorted = SubjectsSorted, Courses = ClassList, Indexs = Indexs)
@app.route('/ProfessorReviewForm/<ProfessorName>', methods = ['GET', 'POST'])
def ProfessorReview(ProfessorName):
if request.method == 'POST':
# Instructor evaluation
CourseName = ' '.join(request.form['CoursesTaughtID'].split(' ')[:-2])
CRN = ''.join(request.form['CoursesTaughtID'].split(' ')[-2])
Term = ''.join(request.form['CoursesTaughtID'].split(' ')[-1])
Grading = int(request.form['GradingID'])
Quality = int(request.form['QualityID'])
Workload = int(request.form['WorkloadID'])
Accessibility = request.form['AccessibilityID']
Syllabus = int(request.form['SyllabusID'])
OptionalDescriptionProfessor = str(request.form['OptionalResponseProfessor'])
# Course Evaluation
CourseToughness = int(request.form['ToughnessID'])
CourseInterest = int(request.form['InterestID'])
TextbookNeeded = int(request.form['TextbookNeeded'])
OptionalDescriptionCourse = str(request.form['OptionalResponseCourse'])
# Add to database
last_name = str(ProfessorName.split(',')[0]) + ','
first_name = str(ProfessorName.split(',')[1])
try:
department = ProfDepartments[ProfessorName]
except:
department = "Unknown"
addProfReview(last_name, first_name, OptionalDescriptionProfessor, Workload, Grading, Quality, Accessibility,Syllabus, department, Professors[last_name + first_name])
addClassReview(last_name, first_name, CourseName, OptionalDescriptionCourse, CourseToughness, CourseInterest, TextbookNeeded, department, CRN, Term, Professors[last_name + first_name])
return render_template('PostSubmissionForm.html', test =' ' )
try:
CoursesTaught = GetCoursesTaught(Professors[ProfessorName])
except KeyError:
CoursesTaught = ["No courses listed"]
num_items = len(CoursesTaught[0]) - 1
RevisedCoursesTaught = []
for i in xrange(len(CoursesTaught)):
if i != 0:
if (CoursesTaught[i][2] != CoursesTaught[i-1][2]) or (CoursesTaught[i][num_items] != CoursesTaught[i-1][num_items]):
RevisedCoursesTaught.append(CoursesTaught[i])
else:
RevisedCoursesTaught.append(CoursesTaught[i])
return render_template('ProfessorReviewForm.html', ProfessorName = ProfessorName, CoursesTaught = RevisedCoursesTaught)
@app.route('/SubmitReviewMain/')
def SubmitReviewMain():
global Professors
ProfessorKeys = Sort_dict(Professors, False)
ProfessorKeys = [i.decode('utf-8') for i in ProfessorKeys]
return render_template('SubmitReviewMain.html', DepartmentKeys = Sort_dict(Options[3], False), DepartmentOptions = Options[3], Professors = Professors, ProfessorKeys = ProfessorKeys)
if __name__=='__main__':
app.run(debug=True)