Skip to content
Permalink
main
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
''' SIMPLE BOOKSHOP WEBSITE BY P. HLINKA '''
from flask import Flask
from markupsafe import escape
from flask import url_for
from flask import render_template
from flask import request
from flask import redirect
from flask import abort
from flask import make_response
from flask import session
from flask import flash
from werkzeug.utils import secure_filename
import sqlite3
import os
app = Flask(__name__)
app.secret_key = "secret key"
UPLOAD_FOLDER = 'static/images/'
ALLOWED_EXTENSIONS = ['jpg']
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def homepage():
"""
https://github.com/HarshShah1997/Shopping-Cart - ADAPTED
Route to display homepage.
"""
if 'user' not in session: #check if user is logged in
return redirect(url_for('login')) #if not redirect to login
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT b.name, b.image, b.isbn FROM books b;") #select from database name and image to display them
data = cur.fetchall() #select also isbn for adding book into the cart
cur.execute("SELECT SUM(quantity) FROM cart WHERE username = ?;", (session["user"],))
nOfBooks = cur.fetchone()[0] #get summary of all books in cart
if nOfBooks == None: #if there aren't any books display 0 instead of None
nOfBooks = 0
cur.execute("SELECT books.retailPrice, cart.quantity FROM books, cart WHERE books.isbn = cart.isbn AND cart.username = ?;", (session["user"],))
price = cur.fetchall()
totalPrice = 0
for row in price: #calculate the total price of books in cart
totalPrice += row[0]*row[1] #row[0] is for price and row[1] is for quantity
session["totalPrice"] = totalPrice #store the data of price and quantity on the server
session["nOfBooks"] = nOfBooks #to use them in other functions
con.close()
return render_template("index.html", user = session["user"], data = data, nOfBooks = nOfBooks, totalPrice = totalPrice)
@app.route('/login', methods=["GET", "POST"])
def login():
"""
5001CEM 2122 GIVEN CODE
Login function to decide either display webpage or do the login.
"""
#if a user submits the form send the data to do_the_login function
if request.method == "POST":
return do_the_login(request.form['username'], request.form['password'])
else:
return render_template('login.html')
def do_the_login(user,pswrd):
"""
5001CEM 2122 GIVEN CODE
Login function.
"""
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT count(*) FROM users WHERE username=? and password=?;", (user,pswrd))
if(int(cur.fetchone()[0])>0): #check if the user is in the database
session["user"] = user #store user's username on the server
con.close()
return redirect(url_for('homepage'))
else:
abort(403)
@app.route("/logout")
def logout():
"""Logout user function."""
session.pop('user', None) #delete user's username from server
return redirect(url_for('login'))
@app.route("/register", methods = ['GET', 'POST'])
def register():
"""Register user function."""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
con = sqlite3.connect('database.db')
try:
cur = con.cursor()
cur.execute('INSERT INTO users ( username, password) VALUES (?, ?)', (username, password)) #store requested data into database
con.commit()
except:
con.rollback()
con.close()
return redirect(url_for('login'))
@app.route("/registrationForm")
def registrationForm():
"""Display registration webpage."""
return render_template("register.html")
@app.route('/stock_levels')
def show_the_stock_levels():
"""Display webpage of stock levels."""
if 'user' not in session:
return redirect(url_for('login'))
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT b.name, b.isbn, b.image, b.quantity FROM books b;")
data = cur.fetchall()
con.close()
totalPrice = session["totalPrice"] #get the data of price and quantity from server
nOfBooks = session ["nOfBooks"] #to display it on the navigation bar
return render_template("stock_levels.html", data = data, totalPrice = totalPrice, nOfBooks = nOfBooks)
@app.route('/stock_levels/add', methods=['GET', 'POST'])
def add():
"""Display webpage to add or update stock."""
if 'user' not in session:
return redirect(url_for('login'))
if request.method == "POST":
return add_books()
else:
return render_template('add_stocks.html')
def add_books():
"""
https://github.com/HarshShah1997/Shopping-Cart - ADAPTED
Add or update books in stock database.
"""
if request.method == "POST":
name = request.form['name'] #get the value from form
author = request.form['author']
date = request.form['datepicker']
isbn = request.form['isbn']
description = request.form['description']
tradePrice = float(request.form['tradePrice'])
retailPrice = float(request.form['retailPrice'])
quantity = int(request.form['quantity'])
#Uploading image procedure
image = request.files['image']
if image and allowed_file(image.filename):
filename = secure_filename(image.filename)
image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
imagename = filename
con = sqlite3.connect('database.db')
try:
cur = con.cursor()
cur.execute("SELECT count(*) FROM books WHERE isbn= ?;", (isbn,))
if(int(cur.fetchone()[0])>0): #check if there is already a book with submitted isbn number
cur.execute("UPDATE books SET quantity = ? WHERE isbn = ?;", (quantity, isbn)) #if True then update the quantity of book in stock with same isbn number
#if there isn't any book with same isbn
#add it to database
else:
cur.execute('INSERT INTO books (name, author, date, isbn, description, image, tradePrice, retailPrice, quantity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);', (name, author, date, isbn, description, imagename, tradePrice, retailPrice, quantity))
con.commit()
except:
con.rollback()
con.close()
return redirect(url_for('homepage'))
@app.route("/addToCart")
def addToCart():
"""Function to add items into cart."""
if 'user' not in session:
return redirect(url_for('login'))
isbn = request.args.get('isbn')
con = sqlite3.connect('database.db')
cur = con.cursor()
try:
cur.execute("SELECT count(*) FROM cart WHERE username = ? AND isbn = ?;", (session["user"], isbn))
if(int(cur.fetchone()[0])>0):
cur.execute("UPDATE cart SET quantity = quantity +1 WHERE isbn=? AND username = ?;", (isbn, session["user"] ))
else:
cur.execute("INSERT INTO cart (username, isbn, quantity) VALUES (?, ?, ?);", (session["user"], isbn, 1))
con.commit()
except:
con.rollback()
con.close()
return redirect(url_for('homepage'))
@app.route("/cart")
def cart():
"""Show cart webpage."""
if 'user' not in session:
return redirect(url_for('login'))
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT books.name, books.image, books.retailPrice, cart.isbn, cart.quantity FROM books, cart WHERE books.isbn = cart.isbn AND username = ?;", (session["user"],))
data = cur.fetchall()
cur.execute("SELECT books.retailPrice, cart.quantity FROM books, cart WHERE books.isbn = cart.isbn AND cart.username = ?;", (session["user"],))
prices = cur.fetchall()
totalPrice = 0
for row in prices: #calculate total price of cart again in case item is removed from cart
totalPrice += row[0]*row[1]
con.close()
session["totalPrice"] = totalPrice
nOfBooks = session ["nOfBooks"]
return render_template('cart.html', data = data, totalPrice = totalPrice, nOfBooks = nOfBooks)
@app.route("/removeFromCart")
def removeFromCart():
"""Remove one item from cart."""
if 'user' not in session:
return redirect(url_for('login'))
isbn = request.args.get('isbn')
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("DELETE FROM cart WHERE username = ? AND isbn = ? ;", (session["user"], isbn))
con.commit()
#Update the quantity of books for navigation bar
cur.execute("SELECT SUM(quantity) FROM cart WHERE username = ?;", (session["user"],))
nOfBooks = cur.fetchone()[0]
if nOfBooks == None:
nOfBooks = 0
con.close()
session["nOfBooks"] = nOfBooks
return redirect(url_for('cart'))
@app.route("/emptyCart")
def emptyCart():
"""Remove all items from cart."""
if 'user' not in session:
return redirect(url_for('login'))
con = sqlite3.connect('database.db')
cur = con.cursor()
try:
cur.execute("DELETE FROM cart WHERE username = ? ;", (session["user"],))
con.commit()
except:
con.rollback()
con.close()
return redirect(url_for('homepage'))
@app.route("/checkout")
def checkout():
"""Check and update the items in cart."""
if 'user' not in session:
return redirect(url_for('login'))
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT books.quantity, cart.quantity, books.isbn, cart.isbn, books.retailPrice FROM books, cart WHERE books.isbn = cart.isbn AND username = ? ;", (session["user"],))
data = cur.fetchall()
totalPrice = session["totalPrice"]
for row in data:
#if the quantity of book in stock is smaller than quantity of selected book in cart
#then change the cart quantity to be equal to the quantity of book in stock
if row[0] < row [1]:
cur.execute("UPDATE cart SET quantity = ? WHERE isbn = ? AND username = ? ;", ( row[0], row[3], session["user"]))
con.commit()
#from cart quantity subtract books quantity
difference = row[1] - row[0]
totalPrice = totalPrice - (difference * row[4]) #update the total price
con.close()
session["totalPrice"] = totalPrice
return redirect(url_for('completeOrder'))
@app.route("/complete_order")
def completeOrder():
"""Display updated version and summary of order."""
if 'user' not in session:
return redirect(url_for('login'))
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT books.name, books.image, books.retailPrice, cart.quantity, books.quantity FROM books, cart WHERE books.isbn = cart.isbn AND username = ?;", (session["user"],))
data = cur.fetchall()
SUMquantity = 0
for row in data: #sum quantity of books in cart
SUMquantity += row[3]
if SUMquantity > 1: #if there is more then one book
postageCost = 2 + SUMquantity #the postageCost is 3 pounds for first book plus 1 pound for every book in cart minus first book
elif SUMquantity == 1:
postageCost = 3
else:
postageCost = 0
con.close()
totalPrice = session["totalPrice"]
nOfBooks = SUMquantity
finalPrice = totalPrice + postageCost
session["finalPrice"] = finalPrice
return render_template('complete_order.html', data = data, totalPrice = totalPrice, finalPrice = finalPrice, postageCost = postageCost, nOfBooks = nOfBooks )
@app.route("/payment")
def payment():
"""Display payment webpage."""
return render_template("payment.html", finalPrice = session["finalPrice"])
@app.route("/paymentDone")
def paymentDone():
"""Update stock and cart after payment."""
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT cart.quantity, cart.isbn FROM cart WHERE username = ?;", (session["user"],))
data = cur.fetchall()
for row in data:
#from stock quantity subtract cart quantity
cur.execute("UPDATE books SET quantity = quantity - ? WHERE isbn = ?;", (row[0], row[1] ))
con.commit()
cur.execute("DELETE FROM cart WHERE username = ?", (session["user"],))
con.commit()
con.close()
flash('Payment successful!')
return redirect(url_for('homepage'))
def allowed_file(filename):
'''https://github.com/HarshShah1997/Shopping-Cart - TAKEN CODE'''
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
if __name__ == '__main__':
app.run(debug=True)