-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
603 lines (496 loc) · 19.1 KB
/
app.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
from flask import Flask, render_template, request, url_for, session, redirect, escape, flash
from passlib.hash import sha256_crypt
import pymysql
from flask_sqlalchemy import SQLAlchemy
import yaml
import collections
app = Flask(__name__)
#Configure db
db = yaml.load(open('db.yaml'))
"""
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
"""
myApp = pymysql.connect(host=db['mysql_host'], user=db['mysql_user'], password=db['mysql_password'], db=db['mysql_db'], charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
profile = True # if profile was filled out
@app.route('/', methods = ["GET"])
def index():
if 'username' in session:
username = session['username']
# check if user filled out profile + has matches
cur = myApp.cursor()
cur.execute("SELECT userID FROM user WHERE username=%s", [username])
userID = cur.fetchone()['userID']
cur.execute("SELECT hackathonID FROM usertohackathon WHERE userID=%s", [userID])
if cur.fetchone() is not None:
return render_template('index.html', username=username, profile=profile)
return render_template('index.html', username=username)
return render_template('index.html')
@app.route('/login', methods = ["GET", "POST"])
def login():
error = None
if 'username' in session:
return redirect(url_for('index'))
if request.method == 'POST':
username_form = request.form['username']
password_form = request.form['password']
cur = myApp.cursor()
cur.execute("SELECT COUNT(1) FROM user WHERE username = %s;", [username_form]) # CHECKS IF USERNAME EXISTS
if cur.fetchone() is not None:
cur.execute("SELECT password FROM user WHERE username = %s;", [username_form]) # FETCH THE PASSWORD
for row in cur.fetchall():
if sha256_crypt.verify(password_form, row['password']):
session['username'] = request.form['username']
cur.close()
return redirect(url_for('index'))
else:
error = "Wrong password"
else:
error = "Username not found"
cur.close()
return render_template('login.html', error=error)
@app.route('/register', methods = ["GET","POST"])
def register():
error = []
isIssue = False
if request.method == 'POST':
# fetch form data
userDetails = request.form
username = userDetails['username']
email = userDetails['email']
password = userDetails['password']
confirm_password = userDetails['confirm_password']
cur = myApp.cursor()
cur.execute("SELECT * FROM user WHERE username = %s", [username])
#error handling
if cur.fetchone() is not None:
error.append('Please choose a different username.')
isIssue = True
cur.execute("SELECT * FROM user WHERE email = %s", [email])
if cur.fetchone() is not None:
error.append('Email already registered.')
isIssue = True
if password != confirm_password:
error.append('Passwords do not match.')
isIssue = True
if isIssue: # if any errors
return render_template('register.html', error = error)
# if no errors, add to database
cur.execute("INSERT INTO user(email, username, password) VALUES(%s, %s, %s)", [email, username, sha256_crypt.encrypt(password)])
myApp.commit()
cur.close()
flash('Congrats! You are now a registered hacker.')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))
@app.route('/preferences', methods = ["GET","POST"])
def prefs():
isError = False
error = []
# redirect to home page if no one is logged in
if 'username' not in session:
return render_template('index.html')
username_session = escape(session['username'])
username = escape(session['username'])
# Render profile page if form was already filled out
cur = myApp.cursor()
cur.execute("SELECT userID FROM user WHERE username=%s", [username])
userID = cur.fetchone()[0]
cur.execute("SELECT hackathonID FROM usertohackathon WHERE userID=%s", [userID])
if cur.fetchone() is not None:
return redirect(url_for('profile', profile=profile))
if request.method == 'POST':
# simple fields
projIdea_form = request.form.get('projIdea', None)
compLevel_form = request.form.get('comp', None)
exper_form = request.form.get('exper', None)
gitLink_form = request.form.get('gitLink', None) # unique
resume_form = request.form.get('resume', None) # unique
#many to many relationships
hackathon_form = request.form['hackathon']
#arrays
tech = request.form.getlist('tech[]')
languages = request.form.getlist('languages[]')
ints = request.form.getlist('interests[]')
hardware = request.form.getlist('hardware[]')
cur = myApp.cursor()
cur.execute("SELECT userID FROM user WHERE username=%s", [username])
userID = cur.fetchone()[0]
# hackathon
cur.execute("SELECT hackathonID FROM hackathons WHERE hackathon=%s", [hackathon_form])
hackathonID = cur.fetchone()[0]
cur.execute("INSERT INTO usertohackathon VALUES(%s, %s)", [userID, hackathonID])
# multiselect fields: cycle through, add each one as a row in many-to-many table
#technologies
if len(tech) != 0:
for i in range(0, len(tech)):
cur.execute("SELECT techID FROM tech WHERE tech=%s", [tech[i]])
techID = cur.fetchone()[0]
cur.execute("INSERT INTO usertotech VALUES(%s, %s)", [userID, techID])
# languages
if len(languages) != 0:
for i in range(0, len(languages)):
cur.execute("SELECT langID FROM langs WHERE lang=%s", [languages[i]])
langID = cur.fetchone()[0]
cur.execute("INSERT INTO usertolang VALUES(%s, %s)", [userID, langID])
# interests
if len(ints) != 0:
for i in range(0, len(ints)):
cur.execute("SELECT intID FROM interests WHERE interest=%s", [ints[i]])
intID = cur.fetchone()[0]
cur.execute("INSERT INTO usertointerests VALUES(%s, %s)", [userID, intID])
# hardware
if len(hardware) != 0:
for i in range(0, len(hardware)):
cur.execute("SELECT hwID FROM hw WHERE hw=%s", [hardware[i]])
hwID = cur.fetchone()[0]
cur.execute("INSERT INTO usertohw VALUES(%s, %s)", [userID, hwID])
if projIdea_form is not None:
cur.execute("UPDATE user SET projIdea=%s WHERE username=%s", [projIdea_form, username])
myApp.commit()
# radio options
if exper_form is not None:
cur.execute("UPDATE user SET exper=%s WHERE username=%s", [exper_form, username])
myApp.commit()
if compLevel_form is not None:
cur.execute("UPDATE user SET comp=%s WHERE username=%s", [compLevel_form, username])
myApp.commit()
# links
if gitLink_form is not None:
cur.execute("SELECT * FROM user WHERE gitLink=%s", [gitLink_form])
if cur.fetchone() is not None:
error.append('GitHub link not unique.')
isError = True
else:
cur.execute("UPDATE user SET gitLink=%s WHERE username=%s", [gitLink_form, username])
myApp.commit()
if resume_form is not None:
cur.execute("SELECT * FROM user WHERE resume=%s", [resume_form])
if cur.fetchone() is not None:
error.append('Resume link not unique.')
isError = True
else:
cur.execute("UPDATE user SET resume=%s WHERE username=%s", [resume_form, username])
myApp.commit()
# if error(s), render template early
if isError:
render_template('prefs.html', error = error)
# fix this message?
flash('Thanks for filling out your profile! Scroll down to explore your matches.')
return redirect(url_for('matches'))
return render_template('prefs.html', username=username_session)
@app.route('/profile', defaults={'username': None})
@app.route('/profile/<username>')
def profile(username):
cur = myApp.cursor()
profile=True # if profile was filled out
username_session = session['username']
if username is None:
username = session['username']
# use select statements, send all vars to template
# cols in user table (one to one relationships)
cur.execute("SELECT userID, projIdea, exper, comp, gitLink, resume, email FROM user WHERE username=%s", [username])
row = cur.fetchone()
userID = row['userID'] # need for many-to-many relationships
projIdea = row['projIdea'] # project idea
exper = row['exper'] # experience level
comp = row['comp'] # competition level
gitLink = row['gitLink'] # github link
resume = row['resume'] # resume link
email = row['email'] # email
# hackathon
cur.execute("SELECT hackathonID FROM usertohackathon WHERE userID=%s", [userID])
hID = cur.fetchone()['hackathonID']
cur.execute("SELECT hackathon FROM hackathons WHERE hackathonID=%s", [hID])
hackathon = cur.fetchone()['hackathon']
# multiselect items: have access to IDs. must select ID, then use it to find name of item in its own table
# technologies
cur.execute("SELECT * FROM usertotech WHERE userID=%s", [userID])
techList = []
for row in cur.fetchall(): # loop through rows in usertotech
techID = row['techID']
cur.execute("SELECT tech FROM tech WHERE techID=%s", [techID])
tech = cur.fetchone()['tech']
techList.append(tech)
if len(techList) == 0:
techList = None
#techList = fetch_list('usertotech', 'tech', 'tech', userID)
# interests
cur.execute("SELECT * FROM usertointerests WHERE userID=%s", [userID])
intList = []
for row in cur.fetchall(): # loop through rows in usertotech
intID = row['intID']
cur.execute("SELECT interest FROM interests WHERE intID=%s", [intID])
interest = cur.fetchone()['interest']
intList.append(interest)
if len(intList) == 0:
intList = None
# languages
cur.execute("SELECT * FROM usertolang WHERE userID=%s", [userID])
langList = []
for row in cur.fetchall(): # loop through rows in usertotech
langID = row['langID']
cur.execute("SELECT lang FROM langs WHERE langID=%s", [langID])
lang = cur.fetchone()['lang']
langList.append(lang)
if len(langList) == 0:
langList = None
# hardware
cur.execute("SELECT * FROM usertohw WHERE userID=%s", [userID])
hwList = []
for row in cur.fetchall(): # loop through rows in usertotech
hwID = row['hwID']
cur.execute("SELECT hw FROM hw WHERE hwID=%s", [hwID])
hw = cur.fetchone()['hw']
hwList.append(hw)
if len(hwList) == 0:
hwList = None
return render_template('profile.html', profile=profile, email=email, username_session=username_session, username=username, hackathon=hackathon, projIdea=projIdea,
techList=techList, intList=intList, langList=langList, hwList=hwList, exper=exper, comp=comp, gitLink=gitLink, resume=resume)
@app.route('/update', methods=["GET", "POST"])
def update():
# redirect to home page if no one is logged in
if 'username' not in session:
return render_template('index.html')
isError = False
error = []
username_session = escape(session['username'])
username = escape(session['username'])
if request.method == 'POST':
# simple fields
projIdea_form = request.form.get('projIdea', None)
compLevel_form = request.form.get('comp', None)
exper_form = request.form.get('exper', None)
gitLink_form = request.form.get('gitLink', None) # unique
resume_form = request.form.get('resume', None) # unique
#many to many relationships
hackathon_form = request.form['hackathon']
#arrays
tech = request.form.getlist('tech[]')
languages = request.form.getlist('languages[]')
ints = request.form.getlist('interests[]')
hardware = request.form.getlist('hardware[]')
cur = myApp.cursor()
cur.execute("SELECT userID FROM user WHERE username=%s", [username])
userID = cur.fetchone()[0]
# hackathon
cur.execute("SELECT hackathonID FROM hackathons WHERE hackathon=%s", [hackathon_form])
hackathonID = cur.fetchone()[0]
cur.execute("UPDATE usertohackathon SET hackathonID=%s WHERE userID=%s", [hackathonID, userID])
# how to do rest of form lol
return render_template('update.html', username=username, profile=profile)
@app.route('/matches', methods = ["GET", "POST"])
def matches():
filterType=None
message = None
matches=None
numResults = 0
currID = None
results=None
username = session['username']
profile = True #if profile was filled out
cur = myApp.cursor()
# userID
cur.execute("SELECT userID FROM user WHERE username=%s", [username])
userID = cur.fetchone()['userID']
# hackathon
cur.execute("SELECT hackathonID FROM usertohackathon WHERE userID=%s", [userID])
hID = cur.fetchone()['hackathonID']
if hID is None: # return early if no profile
return render_template('matches.html', username=username, message=["Oops! Looks like you haven't specified your preferences yet."])
# Generating matches
cur.execute("SELECT hackathon FROM hackathons WHERE hackathonID=%s", [hID])
hackathon = cur.fetchone()['hackathon']
# QUERY ALL OTHER FIELDS FROM CURRENT USER
# technologies
cur.execute("SELECT * FROM usertotech WHERE userID=%s", [userID])
techList = []
for row in cur.fetchall(): # loop through rows in usertotech
techID = row['techID']
cur.execute("SELECT tech FROM tech WHERE techID=%s", [techID])
tech = cur.fetchone()['tech']
techList.append(tech)
if len(techList) == 0:
techList = None
# interests
cur.execute("SELECT * FROM usertointerests WHERE userID=%s", [userID])
intList = []
for row in cur.fetchall(): # loop through rows in usertotech
intID = row['intID']
cur.execute("SELECT interest FROM interests WHERE intID=%s", [intID])
interest = cur.fetchone()['interest']
intList.append(interest)
if len(intList) == 0:
intList = None
# languages
cur.execute("SELECT * FROM usertolang WHERE userID=%s", [userID])
langList = []
for row in cur.fetchall(): # loop through rows in usertotech
langID = row['langID']
cur.execute("SELECT lang FROM langs WHERE langID=%s", [langID])
lang = cur.fetchone()['lang']
langList.append(lang)
if len(langList) == 0:
langList = None
# hardware
cur.execute("SELECT * FROM usertohw WHERE userID=%s", [userID])
hwList = []
for row in cur.fetchall(): # loop through rows in usertotech
hwID = row['hwID']
cur.execute("SELECT hw FROM hw WHERE hwID=%s", [hwID])
hw = cur.fetchone()['hw']
hwList.append(hw)
if len(hwList) == 0:
hwList = None
# exper + comp level
cur.execute("SELECT exper, comp FROM user WHERE userID=%s", [userID])
r = cur.fetchone()
exper = r['exper']
comp = r['comp']
# select users at the same hackathon
# set up dictionaries to keep track of matches per user by category
techMatches = dict()
langMatches = dict()
intMatches = dict()
hwMatches = dict()
# values
match_tech = []
match_langs = []
match_ints = []
match_hw = []
mydict = dict()
numRows = cur.execute("SELECT * FROM user WHERE userID !=%s AND userID IN (SELECT userID FROM usertohackathon WHERE hackathonID=%s)", [userID, hID])
if numRows > 0:
matches = cur.fetchall()
l = []
for row in matches:
currID = row['userID']
user_name = row['username']
# account for experience + comp level
exper_match = row['exper'] # exper = col 6
comp_match = row['comp'] # comp = col 5
if exper == exper_match:
l.insert(0, exper)
if comp == comp_match:
if comp == 'Yes':
l.insert(1, 'Competing')
else:
l.insert(1, 'Not Competing')
if intList is not None:
cur.execute("SELECT * FROM usertointerests WHERE userID=%s",[currID])
ints = cur.fetchall()
for row in ints:
# fetch string from db using id
cur.execute("SELECT interest FROM interests WHERE intID=%s", [row['intID']])
item = cur.fetchone()['interest']
if item in intList:
cur.execute("UPDATE user SET numMatches = numMatches + 1 WHERE userID=%s", [currID]) # update numMatches
l.append(item)
match_ints.append(item)
if techList is not None:
cur.execute("SELECT * FROM usertotech WHERE userID=%s",[currID])
tech = cur.fetchall()
for row in tech:
cur.execute("SELECT tech FROM tech WHERE techID=%s", [row['techID']])
item = cur.fetchone()['tech']
if item in techList:
cur.execute("UPDATE user SET numMatches = numMatches + 1 WHERE userID=%s", [currID]) # update numMatches
l.append(item)
match_tech.append(item)
if langList is not None:
cur.execute("SELECT * FROM usertolang WHERE userID=%s",[currID])
langs = cur.fetchall()
for row in langs:
cur.execute("SELECT lang FROM langs WHERE langID=%s", [row['langID']])
item = cur.fetchone()['lang']
if item in langList:
cur.execute("UPDATE user SET numMatches = numMatches + 1 WHERE userID=%s", [currID]) # update numMatches
l.append(item)
match_langs.append(item)
if hwList is not None:
cur.execute("SELECT * FROM usertohw WHERE userID=%s",[currID])
hw = cur.fetchall()
for row in hw:
cur.execute("SELECT hw FROM hw WHERE hwID=%s", [row['hwID']])
item = cur.fetchone()['hw']
if item in hwList:
cur.execute("UPDATE user SET numMatches = numMatches + 1 WHERE userID=%s", [currID]) # update numMatches
l.append(item)
match_hw.append(item)
#update dict (sending to html)
# key: match's userID
# value: list of matching attributes
mydict[user_name] = l
l = []
# initialize dictionaries that keep track of number of matches per user in each category
# key: username
# value: list of matching attributes
if len(match_tech) > 0:
techMatches[user_name] = match_tech
match_tech = []
if len(match_langs) > 0:
langMatches[user_name] = match_langs
match_langs = []
if len(match_ints) > 0:
intMatches[user_name] = match_ints
match_ints = []
if len(match_hw) > 0:
hwMatches[user_name] = match_hw
match_hw = []
# make results dictionary - will display this in html
# key: username
# value: list of matching attributes
results = dict()
for k in sorted(mydict, key=lambda k: len(mydict[k]), reverse=True):
if len(mydict[k]) > 0:
results[k] = mydict[k]
numResults = len(results)
else:
message = ["Sorry, there are no other Team Builders at your hackathon.","Please check your hackathon's schedule for a team building event!"]
if request.method == 'POST':
dict1 = collections.OrderedDict()
resFilter = request.form.get('resFilter') # filters: tech, interests, languages, hw, exper level, comp
if resFilter == 'tech':
for k in sorted(techMatches, key=lambda k: len(techMatches[k]), reverse=True):
dict1[k] = techMatches[k]
filterType = 'technology'
elif resFilter == 'ints':
for k in sorted(intMatches, key=lambda k: len(intMatches[k]), reverse=True):
dict1[k] = intMatches[k]
filterType = 'interest'
elif resFilter == 'lang':
for k in sorted(langMatches, key=lambda k: len(langMatches[k]), reverse=True):
dict1[k] = langMatches[k]
filterType = 'language'
elif resFilter == 'hw':
for k in sorted(hwMatches, key=lambda k: len(hwMatches[k]), reverse=True):
dict1[k] = hwMatches[k]
filterType = 'hardware'
elif resFilter == 'exper':
for key in results:
if exper in results[key]:
dict1[key] = results[key]
filterType = 'experience level'
elif resFilter == 'comp':
c = ' '
if comp == 'Yes':
c = 'Competing'
else:
c = 'Not competing'
for key in results:
if c in results[key]:
dict1[key] = results[key]
filterType = 'competition level'
numResults = len(dict1)
results = dict1
return render_template('matches.html', filterType=filterType, results = results, currID=currID,profile=profile, username=username, message=message, matches=matches, numResults=numResults)
app.secret_key = 'MVB79L'
if __name__ == '__main__':
app.config['SESSION_TYPE'] = 'filesystem'
app.run(debug=True)