/
app.py
445 lines (332 loc) · 12.3 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
from flask import Flask, render_template, json, request,redirect,session,jsonify, url_for
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
from werkzeug.wsgi import LimitedStream
import uuid
import os
mysql = MySQL()
app = Flask(__name__)
app.secret_key = 'why would I tell you my secret key?'
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mysqlaccount'
app.config['MYSQL_DATABASE_DB'] = 'instaShare'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
# Default setting
pageLimit = 5
class StreamConsumingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
stream = LimitedStream(environ['wsgi.input'],
int(environ['CONTENT_LENGTH'] or 0))
environ['wsgi.input'] = stream
app_iter = self.app(environ, start_response)
try:
stream.exhaust()
for event in app_iter:
yield event
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
app.config['UPLOAD_FOLDER'] = 'static/Uploads'
app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)
@app.route('/')
def main():
return render_template('index1.html')
@app.route('/classic')
def classic():
return render_template('dashboardclassic.html')
@app.route('/general')
def general():
return render_template('dashboard.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
extension = os.path.splitext(file.filename)[1]
f_name = str(uuid.uuid4()) + extension
file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
return json.dumps({'filename':f_name})
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/showAddWish')
def showAddWish():
return render_template('addWish.html')
@app.route('/addUpdateLike',methods=['POST'])
def addUpdateLike():
try:
if session.get('user'):
_wishId = request.form['wish']
_like = request.form['like']
_user = session.get('user')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_AddUpdateLikes',(_wishId,_user,_like))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
cursor.close()
conn.close()
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_getLikeStatus',(_wishId,_user))
result = cursor.fetchall()
return json.dumps({'status':'OK','total':result[0][0],'likeStatus':result[0][1]})
else:
return render_template('error.html',error = 'An error occurred!')
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
conn.close()
@app.route('/getAllWishes')
def getAllWishes():
try:
if session.get('user'):
_user = session.get('user')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_GetAllWishes',(_user,))
result = cursor.fetchall()
wishes_dict = []
for wish in result:
wish_dict = {
'name' : _user,
'Id': wish[0],
'Title': wish[1],
'Description': wish[2],
'FilePath': wish[3],
'Like':wish[4],
'HasLiked':wish[5]}
wishes_dict.append(wish_dict)
return json.dumps(wishes_dict)
else:
return render_template('error.html', error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
@app.route('/showDashboard')
def showDashboard():
return render_template('dashboard.html')
@app.route('/showSignin')
def showSignin():
if session.get('user'):
return render_template('userHome.html')
else:
return render_template('signin.html')
@app.route('/userHome')
def userHome():
if session.get('user'):
return render_template('userHome.html')
else:
return render_template('error.html',error = 'Unauthorized Access')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/deleteWish',methods=['POST'])
def deleteWish():
try:
if session.get('user'):
_id = request.form['id']
_user = session.get('user')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_deleteWish',(_id,_user))
result = cursor.fetchall()
if len(result) is 0:
conn.commit()
return json.dumps({'status':'OK'})
else:
return json.dumps({'status':'An Error occured'})
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return json.dumps({'status':str(e)})
finally:
cursor.close()
conn.close()
@app.route('/getWishById',methods=['POST'])
def getWishById():
try:
if session.get('user'):
_id = request.form['id']
_user = session.get('user')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_GetWishById',(_id,_user))
result = cursor.fetchall()
wish = []
wish.append({'Id':result[0][0],'Title':result[0][1],'Description':result[0][2],'FilePath':result[0][3],'Private':result[0][4],'Done':result[0][5]})
return json.dumps(wish)
else:
return render_template('error.html', error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
@app.route('/getWish',methods=['POST'])
def getWish():
try:
if session.get('user'):
_user = session.get('user')
_limit = pageLimit
_offset = request.form['offset']
_total_records = 0
con = mysql.connect()
cursor = con.cursor()
cursor.callproc('sp_GetWishByUser',(_user,_limit,_offset,_total_records))
wishes = cursor.fetchall()
cursor.close()
cursor = con.cursor()
cursor.execute('SELECT @_sp_GetWishByUser_3');
outParam = cursor.fetchall()
response = []
wishes_dict = []
for wish in wishes:
wish_dict = {
'Id': wish[0],
'Title': wish[1],
'Description': wish[2],
'Date': wish[4]}
wishes_dict.append(wish_dict)
response.append(wishes_dict)
response.append({'total':outParam[0][0]})
return json.dumps(response)
else:
return render_template('error.html', error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html', error = str(e))
@app.route('/addWish',methods=['POST'])
def addWish():
try:
if session.get('user'):
_title = request.form['inputTitle']
_description = request.form['inputDescription']
_user = session.get('user')
if request.form.get('filePath') is None:
_filePath = ''
else:
_filePath = request.form.get('filePath')
if request.form.get('private') is None:
_private = 0
else:
_private = 1
if request.form.get('done') is None:
_done = 0
else:
_done = 1
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_addWish',(_title,_description,_user,_filePath,_private,_done))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return redirect('/userHome')
else:
return render_template('error.html',error = 'An error occurred!')
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
conn.close()
@app.route('/updateWish', methods=['POST'])
def updateWish():
try:
if session.get('user'):
_user = session.get('user')
_title = request.form['title']
_description = request.form['description']
_wish_id = request.form['id']
_filePath = request.form['filePath']
_isPrivate = request.form['isPrivate']
_isDone = request.form['isDone']
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_updateWish',(_title,_description,_wish_id,_user,_filePath,_isPrivate,_isDone))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'status':'OK'})
else:
return json.dumps({'status':'ERROR'})
except Exception as e:
return json.dumps({'status':'Unauthorized access'})
finally:
cursor.close()
conn.close()
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
try:
_username = request.form['inputEmail']
_password = request.form['inputPassword']
# connect to mysql
con = mysql.connect()
cursor = con.cursor()
cursor.callproc('sp_validateLogin',(_username,))
data = cursor.fetchall()
if len(data) > 0:
if (str(data[0][3])==_password):
session['user'] = data[0][0]
return redirect('/showDashboard')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
con.close()
@app.route('/signUp',methods=['POST','GET'])
def signUp():
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password:
# All Good, let's call MySQL
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_createUser',(_name,_email,_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
@app.route('/games')
def games():
return render_template('/games/games-index.html')
@app.route('/tictac')
def tictac():
return render_template('/games/tictac/tic-tac.html')
@app.route('/lovetest')
def lovetest():
return render_template('/games/lovetest/love-test.html')
@app.route('/mathtest')
def mathtest():
return render_template('/games/mathtest/math-test.html')
@app.route('/magicsquare')
def magicsquare():
return render_template('/games/magicsquare/magic-square.html')
@app.route('/hitthedot')
def hitthedot():
return render_template('/games/hitthedot/hit-the-dot.html')
@app.route('/snake')
def snake():
return render_template('/games/snake/snake.html')
if __name__ == "__main__":
app.run(debug=True ,port=8000)