PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/wishapp/app.py

https://gitlab.com/lancezlin/ai
Python | 371 lines | 338 code | 27 blank | 6 comment | 29 complexity | 858d05cce9329b043791bbad337604fe MD5 | raw file
  1. from flask import Flask, render_template, json, request, redirect, session, jsonify, url_for
  2. from flask.ext.mysql import MySQL
  3. from werkzeug import generate_password_hash, check_password_hash
  4. from werkzeug.wsgi import LimitedStream
  5. import uuid
  6. import os
  7. mysql = MySQL()
  8. app = Flask(__name__)
  9. app.secret_key = 'why would I tell you my secret key?'
  10. # MySQL configurations
  11. app.config['MYSQL_DATABASE_USER'] = 'root'
  12. app.config['MYSQL_DATABASE_PASSWORD'] = 'team008'
  13. app.config['MYSQL_DATABASE_DB'] = 'BucketList'
  14. app.config['MYSQL_DATABASE_HOST'] = 'localhost'
  15. mysql.init_app(app)
  16. # Default setting of page limit
  17. pageLimit = 5
  18. class StreamConsumingMiddleware(object):
  19. """docstring for StreamConsumingMiddleware"""
  20. def __init__(self, app):
  21. self.app = app
  22. def __call__(self, environ, start_response):
  23. stream = LimitedStream(environ['wsgi.input'], int(environ['CONTENT_LENGTH'] or 0))
  24. environ['wsgi.input'] = stream
  25. app_iter = self.app(environ, start_response)
  26. try:
  27. stream.exhaust()
  28. for event in app_iter:
  29. yield event
  30. finally:
  31. if hasattr(app_iter, 'close'):
  32. app_iter.close()
  33. app.config['UPLOAD_FOLDER'] = 'static/Uploads'
  34. app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)
  35. @app.route('/')
  36. def main():
  37. return render_template('index.html')
  38. @app.route('/showSignUp')
  39. def showSignUp():
  40. return render_template('signup.html')
  41. @app.route('/showSignin')
  42. def showSignin():
  43. if session.get('user'):
  44. return render_template('userHome.html')
  45. else:
  46. return render_template('signin.html')
  47. @app.route('/logout')
  48. def logout():
  49. session.pop('user', None)
  50. return redirect('/')
  51. @app.route('/userHome')
  52. def userHome():
  53. if session.get('user'):
  54. return render_template('userHome.html')
  55. else:
  56. return render_template('error.html', error = 'Unauthorized Access')
  57. @app.route('/showAddWish')
  58. def showAddWish():
  59. return render_template('addWish.html')
  60. @app.route('/showDashboard')
  61. def showDashboard():
  62. return render_template('dashboard.html')
  63. @app.route('/upload', methods=['GET', 'POST'])
  64. def upload():
  65. if request.method == 'POST':
  66. file = request.files['file']
  67. extension = os.path.splitext(file.filename)[1]
  68. f_name = str(uuid.uuid4()) + extension
  69. file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
  70. return json.dumps({'filename' : f_name})
  71. @app.route('/signUp',methods=['POST','GET'])
  72. def signUp():
  73. try:
  74. _name = request.form['inputName']
  75. _email = request.form['inputEmail']
  76. _password = request.form['inputPassword']
  77. # validate the received values
  78. if _name and _email and _password:
  79. # All Good, let's call MySQL
  80. conn = mysql.connect()
  81. cursor = conn.cursor()
  82. _hashed_password = generate_password_hash(_password)
  83. cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
  84. data = cursor.fetchall()
  85. if len(data) is 0:
  86. conn.commit()
  87. return json.dumps({'message':'User created successfully !'})
  88. else:
  89. return json.dumps({'error':str(data[0])})
  90. else:
  91. return json.dumps({'html':'<span>Enter the required fields</span>'})
  92. except Exception as e:
  93. return json.dumps({'error':str(e)})
  94. finally:
  95. cursor.close()
  96. conn.close()
  97. @app.route('/validateLogin',methods=['POST'])
  98. def validateLogin():
  99. try:
  100. _username = request.form['inputEmail']
  101. _password = request.form['inputPassword']
  102. # connect to mysql
  103. con = mysql.connect()
  104. cursor = con.cursor()
  105. cursor.callproc('sp_validateLogin',(_username,))
  106. data = cursor.fetchall()
  107. if len(data) > 0:
  108. if check_password_hash(str(data[0][3]),_password):
  109. session['user'] = data[0][0]
  110. return redirect('/showDashboard')
  111. else:
  112. return render_template('error.html',error = 'Wrong Email address or Password.')
  113. else:
  114. return render_template('error.html',error = 'Wrong Email address or Password.')
  115. except Exception as e:
  116. return render_template('error.html',error = str(e))
  117. finally:
  118. cursor.close()
  119. con.close()
  120. @app.route('/addWish', methods = ['POST'])
  121. def addWish():
  122. try:
  123. if session.get('user'):
  124. _title = request.form['inputTitle']
  125. _description = request.form['inputDescription']
  126. _user = session.get('user')
  127. if request.form.get('filePath') is None:
  128. _filePath = ''
  129. else:
  130. _filePath = request.form.get('filePath')
  131. if request.form.get('private') is None:
  132. _private = 0
  133. else:
  134. _private = 1
  135. if request.form.get('done') is None:
  136. _done = 0
  137. else:
  138. _done = 1
  139. conn = mysql.connect()
  140. cursor = conn.cursor()
  141. cursor.callproc('sp_addWish', (_title, _description, _user, _filePath, _private, _done))
  142. data = cursor.fetchall()
  143. if len(data) is 0:
  144. conn.commit()
  145. return redirect('/userHome')
  146. else:
  147. return render_template('error.html', error = 'An error occurred!')
  148. else:
  149. return render_template('error.html', error = 'Unauthorized Access!')
  150. except Exception as e:
  151. return render_template('error.html', error = str(e))
  152. finally:
  153. cursor.close()
  154. conn.close()
  155. @app.route('/getWish', methods = ['POST'])
  156. def getWish():
  157. try:
  158. if session.get('user'):
  159. _user = session.get('user')
  160. _limit = pageLimit
  161. _offset = request.form['offset']
  162. _total_records = 0
  163. conn = mysql.connect()
  164. cursor = conn.cursor()
  165. cursor.callproc('sp_GetWishByUser', (_user, _limit, _offset, _total_records))
  166. wishes = cursor.fetchall()
  167. cursor.close()
  168. cursor = conn.cursor()
  169. cursor.execute('SELECT @_sp_GetWishByUser_3');
  170. outParam = cursor.fetchall()
  171. response = []
  172. wishes_dict = []
  173. for wish in wishes:
  174. wish_dict = {
  175. 'Id' : wish[0],
  176. 'Title' : wish[1],
  177. 'Description' : wish[2],
  178. 'Date' : wish[4]
  179. }
  180. wishes_dict.append(wish_dict)
  181. response.append(wishes_dict)
  182. response.append({'total' : outParam[0][0]})
  183. return json.dumps(response)
  184. else:
  185. return render_template('error.html', error = 'Unauthorized Access')
  186. except Exception as e:
  187. return render_template('error.html', error = str(e))
  188. @app.route('/addUpdateLike',methods=['POST'])
  189. def addUpdateLike():
  190. try:
  191. if session.get('user'):
  192. _wishId = request.form['wish']
  193. _like = request.form['like']
  194. _user = session.get('user')
  195. conn = mysql.connect()
  196. cursor = conn.cursor()
  197. cursor.callproc('sp_AddUpdateLikes',(_wishId,_user,_like))
  198. data = cursor.fetchall()
  199. if len(data) is 0:
  200. conn.commit()
  201. cursor.close()
  202. conn.close()
  203. conn = mysql.connect()
  204. cursor = conn.cursor()
  205. cursor.callproc('sp_getLikeStatus',(_wishId,_user))
  206. result = cursor.fetchall()
  207. return json.dumps({'status':'OK','total':result[0][0],'likeStatus':result[0][1]})
  208. else:
  209. return render_template('error.html',error = 'An error occurred!')
  210. else:
  211. return render_template('error.html',error = 'Unauthorized Access')
  212. except Exception as e:
  213. return render_template('error.html',error = str(e))
  214. finally:
  215. cursor.close()
  216. conn.close()
  217. @app.route('/getAllWishes')
  218. def getAllWishes():
  219. try:
  220. if session.get('user'):
  221. _user = session.get('user')
  222. conn = mysql.connect()
  223. cursor = conn.cursor()
  224. cursor.callproc('sp_GetAllWishes',(_user,))
  225. result = cursor.fetchall()
  226. wishes_dict = []
  227. for wish in result:
  228. wish_dict = {
  229. 'Id': wish[0],
  230. 'Title': wish[1],
  231. 'Description': wish[2],
  232. 'FilePath': wish[3],
  233. 'Like':wish[4],
  234. 'HasLiked':wish[5]}
  235. wishes_dict.append(wish_dict)
  236. return json.dumps(wishes_dict)
  237. else:
  238. return render_template('error.html', error = 'Unauthorized Access')
  239. except Exception as e:
  240. return render_template('error.html',error = str(e))
  241. @app.route('/getWishById', methods=['POST'])
  242. def getWishById():
  243. try:
  244. if session.get('user'):
  245. _id = request.form['id']
  246. _user = session.get('user')
  247. conn = mysql.connect()
  248. cursor = conn.cursor()
  249. cursor.callproc('sp_GetWishById', (_id, _user))
  250. result = cursor.fetchall()
  251. wish = []
  252. 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]})
  253. return json.dumps(wish)
  254. else:
  255. return render_template('error.html', error = 'Unauthorized Access')
  256. except Exception as e:
  257. return render_template('error.html', error = str(e))
  258. @app.route('/updateWish', methods=['POST'])
  259. def updateWish():
  260. try:
  261. if session.get('user'):
  262. _user = session.get('user')
  263. _title = request.form['title']
  264. _description = request.form['description']
  265. _wish_id = request.form['id']
  266. _filePath = request.form['filePath']
  267. _isPrivate = request.form['isPrivate']
  268. _isDone = request.form['isDone']
  269. conn = mysql.connect()
  270. cursor = conn.cursor()
  271. cursor.callproc('sp_updateWish',(_title,_description,_wish_id,_user, _filePath, _isPrivate, _isDone))
  272. data = cursor.fetchall()
  273. if len(data) is 0:
  274. conn.commit()
  275. return json.dumps({'status':'OK'})
  276. else:
  277. return json.dumps({'status':'ERROR'})
  278. except Exception as e:
  279. return json.dumps({'status':'Unauthorized access'})
  280. finally:
  281. cursor.close()
  282. conn.close()
  283. @app.route('/deleteWish', methods = ['POST'])
  284. def deleteWish():
  285. try:
  286. if session.get('user'):
  287. _id = request.form['id']
  288. _user = session.get('user')
  289. conn = mysql.connect()
  290. cursor = conn.cursor()
  291. cursor.callproc('sp_deleteWish', (_id, _user))
  292. data = cursor.fetchall()
  293. if len(data) is 0:
  294. conn.commit()
  295. return json.dumps({'status' : 'OK'})
  296. else:
  297. return json.dumps({'status' : 'An ERROR occurred'})
  298. else:
  299. return render_template('error.html', error = 'Unauthorized Access')
  300. except Exception as e:
  301. return json.dumps({'status' : str(e)})
  302. finally:
  303. cursor.close()
  304. conn.close()
  305. if __name__ == "__main__":
  306. app.run(port=5002)