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 flask import Flask, request
from flask import render_template, session
from database.DBManager import DBManager
from hashlib import md5
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/static/images'
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app = Flask(__name__)
app.secret_key = 'z6czFX2rFDB1Hpzqmd6olU11v9wA'
db = DBManager()
# user = session['user']
sid = 'Oy8eMGNvdmJvb2tz'
pid = 'LpLReqmc'
secret = 'z6czFX2rFDB1Hpzqmd6olU11v9wA'
# cart = session['cart']
@app.route('/')
def home(): # put application's code here
"""
It is the first page that is shown when the application is started.
If a user is logged in then his data is retrieved from the database and shown,
otherwise the login button is shown.
"""
books = db.get_stocks()
totCart = 0
count = 0
try:
logged = session['logged']
except KeyError as k:
session['logged'] = 'false'
return render_template("01-home-bookslist.html", books=books, tot_cart=totCart, cart_count=count)
if session['username'] != 'admin':
for item in db.get_cart(session['username']):
book = db.get_book(item[0])
totCart += book.rt_price * item[1]
count += item[1]
return render_template("01-home-bookslist.html", books=books, tot_cart=totCart, cart_count=count)
@app.route('/login', methods=['GET', 'POST'])
def login_page():
"""
When this page is requested with the GET method, the login form is shown.
When the form is sent and the page is requested with the POST method, then
the function that takes care of verifying the data of the form to log in is called.
@return:
"""
if request.method == 'POST':
formData = request.form.to_dict()
return do_the_login(formData['uname'], formData['pwd'])
else:
session['logged'] = 'false'
return render_template('0-login.html')
@app.route('/stocklevel')
def stock():
"""
It retrieves the data relating to the books in stock from the database and shows them on the appropriate page
@return:
"""
books = db.get_stocks()
return render_template("05-stocklevel.html", books=books)
@app.route('/add_stock')
def add_stock():
"""
It shows the page containing the form to add a book to the database
@return:
"""
return render_template("06-addbooktostock.html")
@app.route('/register_in_stock', methods=['POST'])
def register_stock():
"""
Function called when submitting the page / add_stock form.
Retrieves the form data and provides it to the DatabaseManager for adding the book to the database
@return:
"""
if request.method == 'POST':
formData = request.form.to_dict()
db.add_book_stock(
ISBN=formData['ISBNnumber'], qty=formData['stockqty'], name=formData['bookname'],
author=formData['authorname'], publication_date=formData['pubDate'],
description=formData['bookdescr'], image_url=formData['img_url'],
retail_price=formData['retail_price'],
trade_price=formData['trade_price'],
genre=formData['genre']
)
return stock()
@app.route('/add_to_cart/<ISBN>', methods=['GET', 'POST'])
def add_to_cart(ISBN):
"""
Function called up by pressing the "add to cart" button on the / home page.
It registers the book in the database using the DatabaseManager.add_to_cart method
and update the checksum of the logged in user's cart with the new updated data in order
to perform a correct handshake between the app and the payment system
@param ISBN:
@return:
"""
db.add_to_cart(session['username'], ISBN, 1)
cart = db.get_cart(session['username'])
totCart = 0
count = 0
for item in cart:
book = db.get_book(item[0])
totCart += book.rt_price * item[1]
count += item[1]
checksumstr = f"pid={pid:s}&sid={sid:s}&amount={totCart:.1f}&token={secret:s}"
# print('checksumstr is', checksumstr)
checksum = md5(checksumstr.encode('utf-8')).hexdigest()
session['checksum'] = checksum
# print('checksum is', checksum)
session['sid'] = sid
session['pid'] = pid
return home()
@app.route('/cart')
def show_cart():
"""
It retrieves the data relating to the cart of the logged in user from the database and shows them in the template cart.html
@return:
"""
cart = db.get_cart(session['username'])
totCart = 0
count = 0
books = []
for item in cart:
book = db.get_book(item[0])
books.append((book, item[1]))
totCart += book.rt_price * item[1]
count += item[1]
return render_template('03-cart.html', books=books, tot_cart=totCart, cart_count=count)
@app.route('/delete_from_cart/<ISBN>')
def delete_from_cart(ISBN):
"""
Function called upon pressing the "delete from cart" button in the page / cart.
It removes from the database the record relating to the book identified by ISBN
in the cart of the logged in user then shows the cart page
@param ISBN:
@return:
"""
db.remove_from_cart(session['username'], ISBN, 1)
return show_cart()
@app.route('/checkout', methods=['GET', 'POST'])
def checkout():
"""
If requested with the GET method, it shows the payment form.
Once sent, this form shows a page indicating the success of the operation
@return:
"""
if request.method == 'POST':
return render_template("07-success-page.html", name=request.form['first_name'], email=request.form['email'])
return render_template('04-checkout.html')
@app.route('/do_the_login')
def do_the_login(username, password):
"""
It retrieves username data from the database. If the user is not found in the database it shows an error.
It checks that the password matches and logs in; it retrieves the cart data and displays the main page.
It asks for login again if this does not match
@param username:
@param password:
@return:
"""
try:
user = db.get_user(username)
session['username'] = user.username
except BaseException as e:
return e
if password == user.password:
if username != 'admin':
session['cartID'] = db.get_cart(session['username'])
session['logged'] = 'true'
return home()
else:
return render_template('0-login.html')
if __name__ == '__main__':
app.run()