Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from main import app
from flask import Flask,redirect,url_for,render_template,abort,request,abort,make_response,session,g,flash
import sqlite3
from werkzeug.utils import secure_filename
import os
@app.route('/add', methods=['POST'])
def add_product_to_cart():
cursor = None
_quantity = int(request.form['quantity']) #when the add to cart button is pressed it returns the quantity and the unique ISBN that are saved in _quantity and _code
_code = str(request.form['ISBN'])
all_total_price = 0
all_total_quantity = 0
if _quantity and _code and request.method == 'POST':
#code for creating shopping cart is based on 5001CEM (2021), Teaching Materials
con = sqlite3.connect('prime.db')
cur = con.cursor();
cur.execute("SELECT * FROM stock WHERE ISBN=?;", [_code])
row = cur.fetchone()
#session['book'] is a dictionary of dictionaries, which means that each isbn number inside it correlates to some data about a book, which we will later use when creating a shopping cart
itemArray = { str(row[3]) : {'name' : row [0], 'code' : row[3], 'quantity' : _quantity, 'price' : row[6], 'image' : row[5], 'total_price' : _quantity * row[6]}}
print('itemArray is', itemArray)
code = str(row[3])
session.modified = True
if 'book' in session:
print('in session')
if code in session['book']: #if user already added to basket at least one copy of this book
for key, value in session['book'].items(): #search trough the session untill we find the book that needs updating
if code == key:
old_quantity = session['book'][key]['quantity']
total_quantity = old_quantity + _quantity
if total_quantity > row[8]: # if the quantity asked from the add to cart button is more than the stock we use a flash
flash('You cannot add more books than there are in stock same item')
cur.close()
con.close()
return redirect(url_for('homepage'))
session['book'][key]['quantity'] = total_quantity
session['book'][key]['total_price'] = total_quantity * row[6]
else: #if the item is not the first item added and is different from the one allready added we merge the 2 dictionaries
session['book'] = array_merge(session['book'], itemArray)
for key, value in session['book'].items(): # we update the all_total_quantity and all_total_price
individual_quantity = int(session['book'][key]['quantity'])
individual_price = float(session['book'][key]['total_price'])
if individual_quantity > row[8] : # if the quantity asked from the add to cart button is more than the stock we use a flash
flash('You cannot add more books than there are in stock not same item')
con.close()
return redirect(url_for('homepage'))
all_total_quantity = all_total_quantity + individual_quantity
all_total_price = all_total_price + individual_price
else: # if there is no book in the cart we add the first item and update all_total_price and all_total_quantity
session['book'] = itemArray #add the fist instance of a book to the session
all_total_quantity = all_total_quantity + _quantity
all_total_price = all_total_price + _quantity * row[6]
if all_total_quantity > row[8] : # if the quantity asked from the add to cart button is more than the stock we use a flash
flash('You cannot add more books than there are in stock first item')
cur.close()
con.close()
return redirect(url_for('homepage'))
#update the sessions
session['all_total_quantity'] = all_total_quantity
session['all_total_price'] = all_total_price
cur.close()
con.close()
return redirect(url_for('homepage'))
#end of adapted code
@app.route('/homepage', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
if request.form['Submit'] == 'STOCK LEVEL':
return redirect(url_for('stock_level'))
elif request.form['Submit'] == 'LOGOUT':
session.clear() #clears everything from our session
return redirect(url_for('login'))
elif request.form['Submit'] == 'CART':
return redirect(url_for('shopping_cart')) #this function is located in shopping_cart.py file
else:
con = sqlite3.connect('prime.db') # in order to show the books on our page, we first have to get them from our database
cur = con.cursor()
cur.execute("SELECT * FROM stock") #select everything from books table
rows = cur.fetchall() #put it inside a variable
return render_template('homepage.html',page=url_for('homepage'),rows=rows) #render a html file
@app.route('/delete/<string:code>')
def delete_product(code):
#the code for deleting an item from the shopping cart is based on 5001CEM (2021), Teaching Materials
try:
all_total_price = 0
all_total_quantity = 0
session.modified = True
for item in session['book'].items():#iterates trough session['book'] to find the item that needs to be deleted
if item[0] == str(code):
session['book'].pop(item[0], None)
#checks if there is still an item in the cart
if 'book' in session:
#updates all_total_quantity and all_total_price
for key, value in session['book'].items():
individual_quantity = int(session['book'][key]['quantity'])
individual_price = float(session['book'][key]['price'])
all_total_quantity += individual_quantity
all_total_price += individual_price
break
if all_total_quantity == 0: #clear session if all_total_quantity = 0
session.clear()
else:
session['all_total_quantity'] = all_total_quantity #updates all_total_quantity
session['all_total_price'] = all_total_price #updates all_total_price
return redirect(url_for('shopping_cart'))
except Exception as e:
print(e)
#end of adapted code
def array_merge( first_array , second_array ):
#code for creating shopping cart is based on 5001CEM (2021), Teaching Materials
if isinstance( first_array , list ) and isinstance( second_array , list ):
return first_array + second_array
elif isinstance( first_array , dict ) and isinstance( second_array , dict ):
return dict( list( first_array.items() ) + list( second_array.items() ) )
elif isinstance( first_array , set ) and isinstance( second_array , set ):
return first_array.union( second_array )
return False
#end of borrowed code
'''do_payment is not working yet'''
def do_payment():
con = sqlite3.connect('prime.db')
cur = con.cursor()
cur.execute("SELECT * FROM stock") #select everything from books table
rows = cur.fetchall() #put it inside a variable
return render_template('homepage.html',page=url_for('homepage'),rows=rows) #render a html file
#for key, value in session['book'].items():
#not implemented yet
if __name__ == "__main__":
app.run()