Advertisement
Guest User

viewwwwwws

a guest
Jan 24th, 2017
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.93 KB | None | 0 0
  1. """
  2. Routes and views for the flask application.
  3. """
  4. import json
  5. from datetime import datetime
  6. from flask import render_template
  7. from flask import send_from_directory
  8. from flask import request
  9. from FlaskWebProject2 import app
  10. import mysql.connector
  11. import database
  12.  
  13. listdata = [];
  14. counter = 0;
  15.  
  16. @app.route('/')
  17. @app.route('/home')
  18. def home():
  19. """Renders the home page."""
  20. return send_from_directory('templates', "index.html")
  21.  
  22. @app.route('/oldhome')
  23. def oldhome():
  24. return render_template(
  25. 'a.html',
  26. title='Old Home Page',
  27. year=datetime.now().year,
  28. )
  29.  
  30.  
  31.  
  32. @app.route('/getcategories.json', methods=['GET', 'POST'])
  33. def getcategories():
  34. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  35. GCquery = "SELECT DISTINCT tags FROM article;"
  36. print GCquery
  37. executor = db.cursor()
  38. executor.execute(GCquery)
  39.  
  40. collectionString = "tagdata=["
  41. isfirst = True
  42. alreadyhad = []
  43. for tags in executor:
  44. tag = str(tags)[3:-3].split(",")
  45. for seperateTag in tag:
  46.  
  47. if seperateTag != "":
  48. seperateTag = seperateTag.lower()
  49. if seperateTag[0] == " ":
  50. seperateTag = seperateTag[1:]
  51. if seperateTag not in alreadyhad:
  52. if isfirst:
  53. collectionString += "'" + seperateTag + "'"
  54. isfirst = False
  55. else:
  56. collectionString += ",'" + seperateTag + "'"
  57. alreadyhad += [seperateTag]
  58.  
  59.  
  60. collectionString += "]"
  61. db.close()
  62. return collectionString
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73. @app.route("/testdata", methods = ["POST"])
  74. def testmeme():
  75. print request.form
  76. print "AAA"
  77. jsdata = request.form["name"].split(",")
  78. result = []
  79. for i in jsdata :
  80. result += [str(i)]
  81. print result
  82.  
  83. userid = 1
  84. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  85. #query = "INSERT INTO a VALUES (1)"
  86. articleid = []
  87. cursor = db.cursor()
  88. #for loop to rewrite article names in result var with article id
  89. pkquery = "SELECT MAX(invoice_id) FROM invoice;"
  90. cursor.execute(pkquery)
  91. maxPKresult = cursor.fetchone()
  92. maxPKresult = int(maxPKresult[0])
  93. primarykeytouse = 1 + maxPKresult
  94. totalPrice = 0.0
  95. for x in range(0, len(result)):
  96. if result[x] == "Millenium 7;;;; Triangle":
  97. result[x] = 'Millenium 7" Triangle'
  98. articleidquery = "SELECT article_id FROM article a WHERE a.article_name = '" + result[x] + "';"
  99. cursor.execute(articleidquery)
  100. articleid = cursor.fetchone()
  101. result[x] = int(articleid[0])
  102.  
  103. print result[x]
  104.  
  105. pricequery = "SELECT article_price FROM article WHERE article.article_id = " + str(result[x]) + ";"
  106. cursor.execute(pricequery)
  107. totalpriceresult = cursor.fetchone()
  108. totalPrice += float(totalpriceresult[0])
  109. print "total price: " + str(totalPrice)
  110.  
  111. query = "INSERT INTO invoice VALUES (" + str(primarykeytouse) + "," + str(totalPrice) + ", " + str(userid) + ");"
  112. cursor.execute(query)
  113. print "insert into invoice executed"
  114. db.commit()
  115. print "insert into invoice saved"
  116.  
  117. for x in range(0,len(result)):
  118.  
  119. queryTwo = "INSERT INTO invoice_has_article VALUES (" + str(primarykeytouse) + ", " + str(userid) + ",'" + str(result[x]) + "',1,0);"
  120. cursor.execute(queryTwo)
  121. print "insert into invoice_has_article executed"
  122. db.commit()
  123. print "insert into invoice_has_article saved"
  124.  
  125. db.close()
  126. print "items saved in database, execution without error"
  127.  
  128.  
  129. return json.dumps({'status':'OK', 'name': "Succesfully checked out!"})
  130.  
  131. @app.route("/submit")
  132. def submitter():
  133. return send_from_directory('templates', "submit.html")
  134.  
  135. @app.route("/login",methods=["GET"])
  136. def login():
  137. error = None
  138. return send_from_directory("templates" ,'login.html')
  139.  
  140. @app.route('/register')
  141. def register():
  142. return send_from_directory("templates","register.html")
  143.  
  144. @app.route("/registerpost", methods=["POST"])
  145. def registerpost():
  146. print "gotten here"
  147. print(request.form)
  148. username = request.form["username"]
  149. password = request.form["password"]
  150. firstname = request.form["firstname"]
  151. lastname = request.form["lastname"]
  152. email = request.form["email"]
  153. number = request.form["number"]
  154. zipcode = request.form["zipcode"]
  155. city = request.form["city"]
  156. phone = request.form["phone"]
  157. date = request.form["date"]
  158. adress = request.form["adress"]
  159.  
  160. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  161. #query = "INSERT INTO a VALUES (1)"
  162. executor = db.cursor()
  163. query = "INSERT INTO user_credentials VALUES (NULL, '" + username + "','" + firstname + "','" + lastname + "','" + adress + "'," + number + ",'" + zipcode + "','" + city + "'," + phone + ",'" + date + "')"
  164. executor.execute(query)
  165. db.commit()
  166. query = "INSERT INTO user_login VALUES ('" + username + "','" + password + "','" + email + "',0,(SELECT userid FROM user_credentials WHERE username = '" + username + "'))"
  167. executor.execute(query)
  168. db.commit()
  169. db.close()
  170. query = json.dumps({'status':'OK','result':'Cool'})
  171. print "-" + query
  172. return query
  173.  
  174. @app.route("/wishlistpost", methods=["POST"])
  175. def wishlistpost():
  176. result = request.form["itemid"]
  177. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  178. executor = db.cursor()
  179. userID = 1
  180. query = "INSERT INTO wishlist VALUES (" + str(result) + "," + str(userID) + ")"
  181. executor.execute(query)
  182. db.commit()
  183. db.close()
  184. print result
  185. return json.dumps({"status":"OK" ,"result" : "Succesfully Added " })
  186.  
  187. @app.route("/favoritespost", methods=["POST"])
  188. def favoritespost():
  189. result = request.form["itemid"]
  190. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  191. executor = db.cursor()
  192. userID = 1
  193. query = "INSERT INTO favorites VALUES (" + str(result) + "," + str(userID) + ")"
  194. executor.execute(query)
  195. db.commit()
  196. db.close()
  197. print result
  198. return json.dumps({"status":"OK" ,"result" : "Succesfully Added " })
  199.  
  200. @app.route("/loginauth",methods=["POST"])
  201. def authenticator():
  202. username = request.form["user"]
  203. password = request.form["pass"]
  204. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  205. query = "SELECT username FROM user_login WHERE username = '" + username + "' AND password = '" + password + "'"
  206. print query
  207. executor = db.cursor()
  208. executor.execute(query)
  209. counter = 0
  210. newusername = ""
  211. for (user) in executor:
  212. counter += 1
  213. newusername = user
  214. if (counter == 0):
  215. db.close()
  216. return json.dumps({'status':'No Way'})
  217. else:
  218. db.close()
  219. return json.dumps({'status':'OK', 'username': username})
  220.  
  221. @app.route('/contact')
  222. def contact():
  223. """Renders the contact page."""
  224. return render_template(
  225. 'contact.html',
  226. title='Contact',
  227. year=datetime.now().year,
  228. message='Your contact page.'
  229. )
  230.  
  231. @app.route('/about')
  232. def about():
  233. """Renders the about page."""
  234. return render_template(
  235. 'about.html',
  236. title='About',
  237. year=datetime.now().year,
  238. message='Your application description page.'
  239.  
  240. )
  241.  
  242. @app.route('/history')
  243. def history():
  244. """Renders history page."""
  245. return send_from_directory('templates', 'saleshistory.html')
  246.  
  247. @app.route('/favorites')
  248. def favorites():
  249. """Renders favorites page."""
  250. return send_from_directory('templates','favorites.html')
  251.  
  252. @app.route('/wishlist')
  253. def wishlist():
  254. """Renders wishlist page."""
  255. return send_from_directory('templates','wishlist.html')
  256.  
  257. @app.route("/request.json")
  258. def renderdata():
  259. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  260. query = "SELECT * FROM article"
  261. executor = db.cursor()
  262. executor.execute(query)
  263. collectionString = "jsondata=[{\n"
  264. isfirst = True
  265. for (id, name, description, price, site, tags) in executor:
  266. if isfirst:
  267. isfirst = False
  268. else:
  269. collectionString += ",{\n"
  270. print(name)
  271. tagsvalue = str(tags).split(",")
  272. collectionString += ("\t\"id\":\"" + str(id) + "\",\n" + # Puts data in json-ordered string by hand
  273. "\t\"name\":\"" + str(name).replace("'",";;") + "\",\n" +
  274. "\t\"price\":\"" + str(price) + "\",\n" +
  275. "\t\"site\":\"" + str(site) + "\",\n" +
  276. "\t\"description\":\"" + str(description).replace("'",";;") + "\",\n" +
  277. "\t\"tags\":[")
  278. if (len(tagsvalue) > 0 and tagsvalue[0] != ""):
  279. for tag in tagsvalue:
  280. collectionString += '"' + tag + '"'
  281. if not (tagsvalue.index(tag) == (len(tagsvalue) - 1)):
  282. collectionString += ","
  283. else:
  284. collectionString += '""'
  285. collectionString += "]\n}"
  286.  
  287. collectionString += "]"
  288. db.close()
  289. return collectionString
  290.  
  291. @app.route("/getcategoriesproduct", methods=["POST"])
  292. def getcategoriesproduct():
  293. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  294. result = request.form["tags"]
  295. query = "SELECT * FROM article WHERE tags LIKE '%" + str(result) + "%'"
  296. executor = db.cursor()
  297. executor.execute(query)
  298. collectionString = "[{\n"
  299. isfirst = True
  300. for (id, name, description, price, site, tags) in executor:
  301. if isfirst:
  302. isfirst = False
  303. else:
  304. collectionString += ",{\n"
  305. print(name)
  306. tagsvalue = str(tags).split(",")
  307. collectionString += ("\t\"id\":\"" + str(id) + "\",\n" + # Puts data in json-ordered string by hand
  308. "\t\"name\":\"" + str(name).replace("'",";;") + "\",\n" +
  309. "\t\"price\":\"" + str(price) + "\",\n" +
  310. "\t\"site\":\"" + str(site) + "\",\n" +
  311. "\t\"description\":\"" + str(description).replace("'",";;") + "\",\n" +
  312. "\t\"tags\":[")
  313. if (len(tagsvalue) > 0 and tagsvalue[0] != ""):
  314. for tag in tagsvalue:
  315. collectionString += '"' + tag + '"'
  316. if not (tagsvalue.index(tag) == (len(tagsvalue) - 1)):
  317. collectionString += ","
  318. else:
  319. collectionString += '""'
  320. collectionString += "]\n}"
  321.  
  322. collectionString += "]"
  323. db.close()
  324. return collectionString
  325.  
  326.  
  327.  
  328.  
  329.  
  330. @app.route("/wishlist.json")
  331. def getWishlist():
  332. username = "test"
  333. sql1 = " SELECT userid FROM user_credentials WHERE user_credentials.username = '" + username + "';";
  334. collectionString = "wishlistdata=[{\n"
  335. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  336. execute = db.cursor()
  337. execute.execute(sql1)
  338. userid = str(execute.fetchone()[0])
  339. sql2 = "SELECT article.article_name, article.article_description, article.article_price FROM article, wishlist, user_credentials WHERE user_credentials.userid = wishlist.userid AND article.article_id = wishlist.article_id;"
  340. execute.execute(sql2)
  341. WishlistData = execute.fetchall()
  342. first = True;
  343.  
  344. for row in WishlistData:
  345. if (first == False):
  346. collectionString += ",{\n"
  347. else:
  348. first = False;
  349.  
  350. collectionString += ("\t\"name\":\"" + str(row[0]) + "\",\n" +
  351. "\t\"desc\":\"" + str(row[1]) + "\",\n" +
  352. "\t\"price\":\"" + str(row[2]) + "\"}\n")
  353. collectionString += "]"
  354. db.close()
  355. return collectionString
  356.  
  357. @app.route("/saleshistory.json")
  358. def getCustomerSalesHistory():
  359. username = "test"
  360. getUseridQuery = "SELECT userid FROM user_credentials WHERE user_credentials.username = '" + username + "';"
  361. collectionString = "json=[{\n"
  362. db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
  363. cursor = db.cursor()
  364. cursor.execute(getUseridQuery)
  365. userid = str(cursor.fetchone()[0])
  366. query = "SELECT article.article_name, article.article_price, invoice_has_article.amount FROM article, invoice, invoice_has_article, user_credentials WHERE user_credentials.userid = invoice.user_credentials_userid AND invoice.invoice_id = invoice_has_article.invoice_id AND invoice_has_article.article_id = article.article_id AND user_credentials.userid = " + userid + ";"
  367. cursor.execute(query)
  368. salesHistory = cursor.fetchall()
  369. isFirst = True
  370. for row in salesHistory:
  371. if isFirst:
  372. isFirst = False
  373. else:
  374. collectionString += ",{\n"
  375. collectionString += ("\t\"name\":\"" + str(row[0]) + "\",\n" +
  376. "\t\"total_price\":\"" + str(row[1]) + "\",\n" +
  377. "\t\"amount\":\"" + str(row[2]) + "\"\n}")
  378.  
  379. collectionString += "]"
  380. db.close()
  381. return collectionString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement