Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.02 KB | None | 0 0
  1. # Copyright 2013 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __builtin__ import False
  15.  
  16. """
  17. Sample App Engine application demonstrating how to connect to Google Cloud SQL
  18. using App Engine's native unix socket or using TCP when running locally.
  19. For more information, see the README.md.
  20. """
  21.  
  22. # [START all]
  23. from flask import Flask, render_template, request, json
  24. from datetime import datetime
  25. import os, re
  26. import MySQLdb
  27. import app
  28.  
  29. app = Flask(__name__)
  30.  
  31. # These environment variables are configured in app.yaml.
  32. CLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME')
  33. CLOUDSQL_USER = os.environ.get('CLOUDSQL_USER')
  34. CLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD')
  35. CLOUDSQL_DB = os.environ.get('CLOUDSQL_DB')
  36.  
  37.  
  38. def connect_to_cloudsql():
  39. # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
  40. # will be set to 'Google App Engine/version'.
  41. if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
  42. # Connect using the unix socket located at
  43. # /cloudsql/cloudsql-connection-name.
  44. cloudsql_unix_socket = os.path.join(
  45. '/cloudsql', CLOUDSQL_CONNECTION_NAME)
  46.  
  47. db = MySQLdb.connect(
  48. unix_socket=cloudsql_unix_socket,
  49. user=CLOUDSQL_USER,
  50. passwd=CLOUDSQL_PASSWORD,
  51. db=CLOUDSQL_DB)
  52.  
  53. # If the unix socket is unavailable, then try to connect using TCP. This
  54. # will work if you're running a local MySQL server or using the Cloud SQL
  55. # proxy, for example:
  56. #
  57. # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
  58. #
  59. else:
  60. db = MySQLdb.connect(
  61. host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD)
  62. return db
  63.  
  64.  
  65. @app.route("/")
  66. def main():
  67. return render_template('home.html')
  68.  
  69. @app.route("/rate")
  70. def rate():
  71. conn = connect_to_cloudsql()
  72. cursor = conn.cursor()
  73. q = "SELECT abbr, Course.id, num, description FROM Course, Department WHERE Course.dept = Department.id"
  74. cursor.execute(q)
  75. conn.commit()
  76. data = cursor.fetchall()[:1000]
  77.  
  78. p = "SELECT * from Tag GROUP BY Category, id, name"
  79. cursor.execute(p)
  80. conn.commit()
  81. data2 = cursor.fetchall()
  82.  
  83. s = "SELECT id, name from Professor"
  84. cursor.execute(s)
  85. conn.commit()
  86. data4 = cursor.fetchall()
  87.  
  88.  
  89. return render_template('rate.html', courses=data, tags=data2, profs=data4)
  90.  
  91. @app.route("/search")
  92. def search():
  93. conn = connect_to_cloudsql()
  94. cursor = conn.cursor()
  95. q = "SELECT name, id, abbr from Department"
  96. cursor.execute(q)
  97. conn.commit()
  98. data = cursor.fetchall()
  99.  
  100. p = "SELECT * from Tag GROUP BY Category, id, name"
  101. cursor.execute(p)
  102. conn.commit()
  103. data2 = cursor.fetchall()
  104. return render_template('search.html', courses=data, tags=data2)
  105.  
  106. @app.route('/rate_course/<int:myClass>',methods=['POST', 'GET'])
  107. def rate_course(myClass):
  108. try:
  109. # read the posted values from the UI
  110. _class = str(myClass)
  111. # validate the received values
  112. if True:
  113. conn = connect_to_cloudsql()
  114. cursor = conn.cursor()
  115. #cursor.execute("SELECT * FROM Department")
  116. q = "SELECT * from Course WHERE id = " + _class
  117. cursor.execute(q)
  118. conn.commit()
  119. #cursor.execute("""INSERT INTO Department (id, name, abbr) VALUES (2, 'bleh', 'compsci')""")
  120. data = cursor.fetchall()[0] #list(cursor)
  121.  
  122. p = "SELECT * from Tag GROUP BY Category, id, name"
  123. cursor.execute(p)
  124. conn.commit()
  125. data2 = cursor.fetchall()
  126.  
  127. r = "SELECT * from Attribute"
  128. cursor.execute(r)
  129. conn.commit()
  130. data3 = cursor.fetchall()
  131.  
  132. s = "SELECT id, name from Professor"
  133. cursor.execute(s)
  134. conn.commit()
  135. data4 = cursor.fetchall()
  136.  
  137. return render_template('rate-class.html', course=data, tags=data2, course_attributes=data3, profs=data4)
  138. # if len(data) is 0:
  139. # conn.commit()
  140. # return json.dumps({'error1': 'no matching data'})
  141. # else:
  142. # return json.dumps({'message':str(data[0])})
  143. # else:
  144. # return json.dumps({'html':'<span>Enter the required fields</span>'})
  145.  
  146. except Exception as e:
  147. return json.dumps({'error2':str(e)})
  148.  
  149. @app.route("/submit_rating", methods=['POST', 'GET'])
  150. def submit_rating():
  151. try:
  152. # read the posted values from the UI
  153. _tags = request.form.getlist('tag')
  154. _semester = request.form.getlist('semester')[0]
  155. _year = request.form.get('year')
  156. _prof = request.form.get('prof')
  157. course = 393#request.form.get('hiddenInputClass')
  158.  
  159. # validate the received values
  160. if _tags:
  161. conn = connect_to_cloudsql()
  162. cursor = conn.cursor()
  163.  
  164. q = "SELECT id FROM Class WHERE course = %s and teacher = %s"
  165. cursor.execute(q, (str(course), _prof))
  166. data = cursor.fetchall()
  167.  
  168. if len(data) == 0:
  169. p = "INSERT INTO Class(course, teacher) VALUES (%s, %s)"
  170. cursor.execute(p, (str(course), _prof))
  171. t = "SELECT id FROM Class WHERE course = %s and teacher = %s"
  172. cursor.execute(t, (str(course), _prof))
  173. class_id = cursor.fetchall()[0]
  174. else:
  175. class_id = data[0][0]
  176. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  177. for tag in _tags:
  178. r = "INSERT INTO Tag_Reviews(tag_date, class_id, tag, semester, year) VALUES (%s, %s, %s, %s, %s)"
  179. cursor.execute(r, (timestamp, str(class_id), str(tag), _semester, _year))
  180. data = cursor.fetchall()
  181.  
  182. if len(data) is 0:
  183. conn.commit()
  184. return open_class(int(class_id))
  185. else:
  186. return json.dumps({'error':str(data[0])})
  187. else:
  188. return json.dumps({'html':'<span>Enter the required fields</span>'})
  189.  
  190. except Exception as e:
  191. return json.dumps({'error':str(e)})
  192.  
  193. @app.route('/submit_search',methods=['POST', 'GET'])
  194. def submit_search():
  195. try:
  196. # read the posted values from the UI
  197. _dept = request.form['inputClass']
  198. _num = request.form['num']
  199. _prof = request.form['prof']
  200. _attributes = request.form.getlist('attribute')
  201. _tag_ids = request.form.getlist('tag')
  202.  
  203. conn = connect_to_cloudsql()
  204. cursor = conn.cursor()
  205.  
  206. _tags = []
  207. for tag in _tag_ids:
  208. tag_id_q = "SELECT name FROM Tag WHERE id=%s" %(tag)
  209. cursor.execute(tag_id_q)
  210. _tags.append(cursor.fetchall()[0][0])
  211.  
  212. # validate the received values
  213. if _dept or _num or _prof or _tags or _attributes:
  214.  
  215. conditions = []
  216.  
  217. course_conditions = []
  218. if _dept:
  219. course_conditions.append("dept = (SELECT id FROM Department WHERE name='" + _dept + "')")
  220. if _num:
  221. course_conditions.append("num ='" + _num + "'")
  222. if course_conditions != []:
  223. course_condition = "cl.course IN (SELECT id FROM Course WHERE %s)" %(" and ".join(course_conditions))
  224. conditions.append(course_condition)
  225.  
  226. if _prof:
  227. prof_condition = "cl.teacher = (SELECT id FROM Professor WHERE name LIKE '%%%s%%')" %(_prof)
  228. conditions.append(prof_condition)
  229.  
  230. if conditions:
  231. classes = "SELECT cl.id AS class_id, cl.course AS course_id, cl.teacher AS prof_id FROM Class cl WHERE %s" %(" and ".join(conditions))
  232. else:
  233. classes = "SELECT id AS class_id, course AS course_id, teacher AS prof_id FROM Class"
  234. q = "SELECT c1.class_id, co.dept, co.num, p.name FROM (%s) AS c1, Course co, Professor p WHERE c1.course_id = co.id AND p.id = c1.prof_id" %(classes)
  235. cursor.execute(q)
  236. data = cursor.fetchall()
  237. #return json.dumps({'data':data, 'query': q})
  238. classes = {}
  239. for id, dept, num, prof in data:
  240. tag_q = "SELECT t.name FROM Tag_Reviews r, Tag t WHERE r.class_id = %s AND t.id = r.tag" %(str(id))
  241. cursor.execute(tag_q)
  242. tag_data = cursor.fetchall()
  243. print tag_data
  244. tags = list(set([t[0] for t in tag_data]))
  245.  
  246. attribute_q = "SELECT a.name FROM Attribute a, (SELECT attribute_id FROM Course_Attributes c WHERE c.course_id = %s) AS ai WHERE a.id = ai.attribute_id" %(str(id))
  247. cursor.execute(attribute_q)
  248. attribute_data = cursor.fetchall()
  249. attributes = list(set([a[0] for a in attribute_data]))
  250.  
  251. dept_q = "SELECT abbr FROM Department where id = %s" %(dept)
  252. cursor.execute(dept_q)
  253. dept_name = cursor.fetchall()[0][0]
  254.  
  255. classes[id] = (dept_name+num, prof, attributes, tags)
  256.  
  257. scores = []
  258. res =[]
  259. for key, val in classes.iteritems():
  260. class_attributes = val[2]
  261. class_tags = val[3]
  262. attribute_intersect = len(set(class_attributes).intersection(set(_attributes)))
  263. tag_intersect = len(set(class_tags).intersection(set(_tags)))
  264. if ((_attributes != [] and attribute_intersect > 0) or _attributes==[]) and ((_tags != [] and tag_intersect > 0) or _tags==[]):
  265. score = attribute_intersect + tag_intersect
  266. res.append((key, val, score))
  267. scores.append((_tags, tag_intersect))
  268.  
  269. res = sorted(sorted(res, key=lambda x: x[1]), key=lambda x: x[2], reverse=True)
  270. res = [(key, val) for key, val, score in res]
  271.  
  272. conn.commit()
  273. noResults = False
  274. if len(res) == 0:
  275. noResults = True
  276. return render_template('result.html', result=res, noResults=noResults)
  277.  
  278. else:
  279. return json.dumps({'html':'<span>Enter the required fields</span>'})
  280.  
  281. except Exception as e:
  282. return json.dumps({'error':str(e), 'query': q})
  283.  
  284. @app.route('/open_class/<int:c>',methods=['POST', 'GET'])
  285. def open_class(c):
  286. try:
  287. # read the posted values from the UI
  288. conn = connect_to_cloudsql()
  289. cursor = conn.cursor()
  290. q = "SELECT t.tag_date, name, t.semester, t.year FROM Tag, (SELECT tag_date, tag, semester, year FROM Tag_Reviews WHERE class_id = %s) t WHERE t.tag = id" %(str(c))
  291. cursor.execute(q)
  292. conn.commit()
  293. data = cursor.fetchall()
  294.  
  295. reviews = {}
  296. for date, tag, season, year in data:
  297. if date not in reviews:
  298. reviews[date] = (season + " " + str(year), set([]))
  299. time, tags = reviews[date]
  300. tags.add(tag)
  301. reviews[date] = (time, tags)
  302. return render_template("class.html", ratings=reviews)
  303.  
  304. except Exception as e:
  305. return json.dumps({'error':str(e)})
  306.  
  307. if __name__ == "__main__":
  308. app.run()
  309.  
  310. # [END all]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement