Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Routes and views for the flask application.
- """
- import json
- from datetime import datetime
- from flask import render_template
- from flask import send_from_directory
- from flask import request
- from FlaskWebProject2 import app
- import mysql.connector
- import database
- listdata = [];
- counter = 0;
- @app.route('/')
- @app.route('/home')
- def home():
- """Renders the home page."""
- return send_from_directory('templates', "index.html")
- @app.route('/oldhome')
- def oldhome():
- return render_template(
- 'a.html',
- title='Old Home Page',
- year=datetime.now().year,
- )
- @app.route('/getcategories.json', methods=['GET', 'POST'])
- def getcategories():
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- GCquery = "SELECT DISTINCT tags FROM article;"
- print GCquery
- executor = db.cursor()
- executor.execute(GCquery)
- collectionString = "tagdata=["
- isfirst = True
- alreadyhad = []
- for tags in executor:
- tag = str(tags)[3:-3].split(",")
- for seperateTag in tag:
- if seperateTag != "":
- seperateTag = seperateTag.lower()
- if seperateTag[0] == " ":
- seperateTag = seperateTag[1:]
- if seperateTag not in alreadyhad:
- if isfirst:
- collectionString += "'" + seperateTag + "'"
- isfirst = False
- else:
- collectionString += ",'" + seperateTag + "'"
- alreadyhad += [seperateTag]
- collectionString += "]"
- db.close()
- return collectionString
- @app.route("/testdata", methods = ["POST"])
- def testmeme():
- print request.form
- print "AAA"
- jsdata = request.form["name"].split(",")
- result = []
- for i in jsdata :
- result += [str(i)]
- print result
- userid = 1
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- #query = "INSERT INTO a VALUES (1)"
- articleid = []
- cursor = db.cursor()
- #for loop to rewrite article names in result var with article id
- pkquery = "SELECT MAX(invoice_id) FROM invoice;"
- cursor.execute(pkquery)
- maxPKresult = cursor.fetchone()
- maxPKresult = int(maxPKresult[0])
- primarykeytouse = 1 + maxPKresult
- totalPrice = 0.0
- for x in range(0, len(result)):
- if result[x] == "Millenium 7;;;; Triangle":
- result[x] = 'Millenium 7" Triangle'
- articleidquery = "SELECT article_id FROM article a WHERE a.article_name = '" + result[x] + "';"
- cursor.execute(articleidquery)
- articleid = cursor.fetchone()
- result[x] = int(articleid[0])
- print result[x]
- pricequery = "SELECT article_price FROM article WHERE article.article_id = " + str(result[x]) + ";"
- cursor.execute(pricequery)
- totalpriceresult = cursor.fetchone()
- totalPrice += float(totalpriceresult[0])
- print "total price: " + str(totalPrice)
- query = "INSERT INTO invoice VALUES (" + str(primarykeytouse) + "," + str(totalPrice) + ", " + str(userid) + ");"
- cursor.execute(query)
- print "insert into invoice executed"
- db.commit()
- print "insert into invoice saved"
- for x in range(0,len(result)):
- queryTwo = "INSERT INTO invoice_has_article VALUES (" + str(primarykeytouse) + ", " + str(userid) + ",'" + str(result[x]) + "',1,0);"
- cursor.execute(queryTwo)
- print "insert into invoice_has_article executed"
- db.commit()
- print "insert into invoice_has_article saved"
- db.close()
- print "items saved in database, execution without error"
- return json.dumps({'status':'OK', 'name': "Succesfully checked out!"})
- @app.route("/submit")
- def submitter():
- return send_from_directory('templates', "submit.html")
- @app.route("/login",methods=["GET"])
- def login():
- error = None
- return send_from_directory("templates" ,'login.html')
- @app.route('/register')
- def register():
- return send_from_directory("templates","register.html")
- @app.route("/registerpost", methods=["POST"])
- def registerpost():
- print "gotten here"
- print(request.form)
- username = request.form["username"]
- password = request.form["password"]
- firstname = request.form["firstname"]
- lastname = request.form["lastname"]
- email = request.form["email"]
- number = request.form["number"]
- zipcode = request.form["zipcode"]
- city = request.form["city"]
- phone = request.form["phone"]
- date = request.form["date"]
- adress = request.form["adress"]
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- #query = "INSERT INTO a VALUES (1)"
- executor = db.cursor()
- query = "INSERT INTO user_credentials VALUES (NULL, '" + username + "','" + firstname + "','" + lastname + "','" + adress + "'," + number + ",'" + zipcode + "','" + city + "'," + phone + ",'" + date + "')"
- executor.execute(query)
- db.commit()
- query = "INSERT INTO user_login VALUES ('" + username + "','" + password + "','" + email + "',0,(SELECT userid FROM user_credentials WHERE username = '" + username + "'))"
- executor.execute(query)
- db.commit()
- db.close()
- query = json.dumps({'status':'OK','result':'Cool'})
- print "-" + query
- return query
- @app.route("/wishlistpost", methods=["POST"])
- def wishlistpost():
- result = request.form["itemid"]
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- executor = db.cursor()
- userID = 1
- query = "INSERT INTO wishlist VALUES (" + str(result) + "," + str(userID) + ")"
- executor.execute(query)
- db.commit()
- db.close()
- print result
- return json.dumps({"status":"OK" ,"result" : "Succesfully Added " })
- @app.route("/favoritespost", methods=["POST"])
- def favoritespost():
- result = request.form["itemid"]
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- executor = db.cursor()
- userID = 1
- query = "INSERT INTO favorites VALUES (" + str(result) + "," + str(userID) + ")"
- executor.execute(query)
- db.commit()
- db.close()
- print result
- return json.dumps({"status":"OK" ,"result" : "Succesfully Added " })
- @app.route("/loginauth",methods=["POST"])
- def authenticator():
- username = request.form["user"]
- password = request.form["pass"]
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- query = "SELECT username FROM user_login WHERE username = '" + username + "' AND password = '" + password + "'"
- print query
- executor = db.cursor()
- executor.execute(query)
- counter = 0
- newusername = ""
- for (user) in executor:
- counter += 1
- newusername = user
- if (counter == 0):
- db.close()
- return json.dumps({'status':'No Way'})
- else:
- db.close()
- return json.dumps({'status':'OK', 'username': username})
- @app.route('/contact')
- def contact():
- """Renders the contact page."""
- return render_template(
- 'contact.html',
- title='Contact',
- year=datetime.now().year,
- message='Your contact page.'
- )
- @app.route('/about')
- def about():
- """Renders the about page."""
- return render_template(
- 'about.html',
- title='About',
- year=datetime.now().year,
- message='Your application description page.'
- )
- @app.route('/history')
- def history():
- """Renders history page."""
- return send_from_directory('templates', 'saleshistory.html')
- @app.route('/favorites')
- def favorites():
- """Renders favorites page."""
- return send_from_directory('templates','favorites.html')
- @app.route('/wishlist')
- def wishlist():
- """Renders wishlist page."""
- return send_from_directory('templates','wishlist.html')
- @app.route("/request.json")
- def renderdata():
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- query = "SELECT * FROM article"
- executor = db.cursor()
- executor.execute(query)
- collectionString = "jsondata=[{\n"
- isfirst = True
- for (id, name, description, price, site, tags) in executor:
- if isfirst:
- isfirst = False
- else:
- collectionString += ",{\n"
- print(name)
- tagsvalue = str(tags).split(",")
- collectionString += ("\t\"id\":\"" + str(id) + "\",\n" + # Puts data in json-ordered string by hand
- "\t\"name\":\"" + str(name).replace("'",";;") + "\",\n" +
- "\t\"price\":\"" + str(price) + "\",\n" +
- "\t\"site\":\"" + str(site) + "\",\n" +
- "\t\"description\":\"" + str(description).replace("'",";;") + "\",\n" +
- "\t\"tags\":[")
- if (len(tagsvalue) > 0 and tagsvalue[0] != ""):
- for tag in tagsvalue:
- collectionString += '"' + tag + '"'
- if not (tagsvalue.index(tag) == (len(tagsvalue) - 1)):
- collectionString += ","
- else:
- collectionString += '""'
- collectionString += "]\n}"
- collectionString += "]"
- db.close()
- return collectionString
- @app.route("/getcategoriesproduct", methods=["POST"])
- def getcategoriesproduct():
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- result = request.form["tags"]
- query = "SELECT * FROM article WHERE tags LIKE '%" + str(result) + "%'"
- executor = db.cursor()
- executor.execute(query)
- collectionString = "[{\n"
- isfirst = True
- for (id, name, description, price, site, tags) in executor:
- if isfirst:
- isfirst = False
- else:
- collectionString += ",{\n"
- print(name)
- tagsvalue = str(tags).split(",")
- collectionString += ("\t\"id\":\"" + str(id) + "\",\n" + # Puts data in json-ordered string by hand
- "\t\"name\":\"" + str(name).replace("'",";;") + "\",\n" +
- "\t\"price\":\"" + str(price) + "\",\n" +
- "\t\"site\":\"" + str(site) + "\",\n" +
- "\t\"description\":\"" + str(description).replace("'",";;") + "\",\n" +
- "\t\"tags\":[")
- if (len(tagsvalue) > 0 and tagsvalue[0] != ""):
- for tag in tagsvalue:
- collectionString += '"' + tag + '"'
- if not (tagsvalue.index(tag) == (len(tagsvalue) - 1)):
- collectionString += ","
- else:
- collectionString += '""'
- collectionString += "]\n}"
- collectionString += "]"
- db.close()
- return collectionString
- @app.route("/wishlist.json")
- def getWishlist():
- username = "test"
- sql1 = " SELECT userid FROM user_credentials WHERE user_credentials.username = '" + username + "';";
- collectionString = "wishlistdata=[{\n"
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- execute = db.cursor()
- execute.execute(sql1)
- userid = str(execute.fetchone()[0])
- 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;"
- execute.execute(sql2)
- WishlistData = execute.fetchall()
- first = True;
- for row in WishlistData:
- if (first == False):
- collectionString += ",{\n"
- else:
- first = False;
- collectionString += ("\t\"name\":\"" + str(row[0]) + "\",\n" +
- "\t\"desc\":\"" + str(row[1]) + "\",\n" +
- "\t\"price\":\"" + str(row[2]) + "\"}\n")
- collectionString += "]"
- db.close()
- return collectionString
- @app.route("/saleshistory.json")
- def getCustomerSalesHistory():
- username = "test"
- getUseridQuery = "SELECT userid FROM user_credentials WHERE user_credentials.username = '" + username + "';"
- collectionString = "json=[{\n"
- db = mysql.connector.connect(user="esso_php", passwd=database.returnPassword() , host="bull-ict.nl",database="esso_php")
- cursor = db.cursor()
- cursor.execute(getUseridQuery)
- userid = str(cursor.fetchone()[0])
- 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 + ";"
- cursor.execute(query)
- salesHistory = cursor.fetchall()
- isFirst = True
- for row in salesHistory:
- if isFirst:
- isFirst = False
- else:
- collectionString += ",{\n"
- collectionString += ("\t\"name\":\"" + str(row[0]) + "\",\n" +
- "\t\"total_price\":\"" + str(row[1]) + "\",\n" +
- "\t\"amount\":\"" + str(row[2]) + "\"\n}")
- collectionString += "]"
- db.close()
- return collectionString
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement