def returnBook(self, user): """ allow the user to return a book Paramters: user """ # prompt the user to choose between entering the ISBN manually or scanning the QR code option = int( input( 'Please choose\n 1.Manually Enter the detail\n 2.Return the book using QR code \n' )) if option == 1: # prompt the user for the book ISBN user_input = input( 'Please type your book ISBN to continue with return process\n') # if user choses to scan a QR code elif option == 2: # call the barcodescanner file user_input = barcodescanner.scanQR() # strip the ISBN if it has spaces user_input = user_input.strip() # if the ISBN code does not match the format then exit if user_input == "quitbyuser": exit # call DatabaseUtils class and create an object of it db_object = DatabaseUtils() # get today's date now = datetime.datetime.now() today_date = now.strftime("%Y-%m-%d") # check if the user typed the ISBN regex = r'978[\d\-]+\d' pattern = re.match(regex, user_input) if bool(pattern) == True: # check if the book has been borrowed at the first place return_value, t_value = db_object.checkIfBookExistsInBookBorrowed( user_input, user) if isinstance(return_value, int) and t_value == True: id_event = '00000' + str(return_value) # remove the event from Google Calendar bookevent.removeEvent(id_event) # update the status of the book in BookBorrowed table db_object.updateBookBorrowed(user, return_value, 'returned', today_date) # print a message to the user print('We hope that you enjoyed your journey reading the book') return True # if the book doesn't exist in the BookBorrowed table, then it means the book has not been borrowed else: print( 'We apologize, the ISBN you entered has not been borrowed by you!' ) return False # if the user typed something else rather than book ISBN else: print('Your Input does not match books ISBN') return False
class Test_databaseUtils(unittest.TestCase): def setUp(self): self.db=DatabaseUtils() self.db.createUsersTable() def dataCount(self): conn=self.db.createConnection() cur=conn.cursor() try: cur.execute("select count(*) from Users") row = cur.fetchone() conn.commit() conn.close() return row[0] except: conn.close() raise Exception("Search data counts fail!") def test_insertNewUser(self): trueData=("username", "password", "firstname", "lastname", "email") self.assertEqual(self.dataCount(),0) trueOne = self.db.insertNewUser(trueData) self.assertTrue(trueOne) self.assertEqual(self.dataCount(),1) falseData="anything" falseOne = self.db.insertNewUser(falseData) self.assertFalse(falseOne) self.assertNotEqual(self.dataCount(),2) def test_searchUserPassword(self): trueData=("username") password = self.db.searchUserPassword(trueData) if(password[0]!=None): if(password[0]=="password"): print("Test passed") else: print("Test Failed") else: print("Test Failed") wrongData=("username1") anotherPassword = self.db.searchUserPassword(wrongData) if(anotherPassword!=None): print("Test failed") else: print("Test passed") def test_searchUserData(self): matchData=("username", "firstname", "lastname") trueData=("username") userData = self.db.searchUserData(trueData) self.assertEqual(userData,matchData) trueData=("username1") userData = self.db.searchUserData(trueData) self.assertNotEqual(userData,matchData)
def insertUser(self, name): with DatabaseUtils() as db: if (db.insertUser(name)): # print("{} inserted successfully.".format(name)) pass else: print("{} failed to be inserted.".format(name))
def test_insertPerson(self): with DatabaseUtils(self.connection) as db: count = self.countPeople() self.assertTrue(db.insertPerson("Kevin")) self.assertTrue(count + 1 == self.countPeople()) self.assertTrue(db.insertPerson("Ryan")) self.assertTrue(count + 2 == self.countPeople())
def userLogin(self, username, password): """ Parameters ---------- username : str user name password : str password """ with DatabaseUtils() as db: inputData = (username) hashedPassword = db.searchUserPassword(inputData) if (hashedPassword != None): #check password hashPassword = hashedPassword[0] if (sha256_crypt.verify(password, hashPassword)): print("Usename {} Login sucessfully.".format(username)) #then call Jun function to connect with another rasp pi loginUserData = db.searchUserData(inputData) userName = loginUserData[0] realName = loginUserData[1] + " " + loginUserData[2] socketClient(userName, realName).mainRun() else: print("Usename {} password incorrect, Login fail".format( username)) else: print( "Login fail coz usename {} is not exist.".format(username))
def newUserRegister(self, username, password, firstname, lastname, email): """ Parameters ---------- username : str user name password : str password firstname : str user first name lastname : str user last name email : str email """ with DatabaseUtils() as db: #put all data into a tuple inputData = (username, password, firstname, lastname, email) #check insert data suceess or fail if (db.insertNewUser(inputData) == True): print("Username is {} ,Data inserted successfully.".format( username)) else: print("Data failed to be inserted coz {} exist.".format( username))
def test_insertBook(self): with DatabaseUtils(self.connection) as db: count = self.countBook() self.assertTrue(db.insertBook("book4", "auth4", "2010-10-10")) self.assertTrue(count + 1 == self.countBook()) self.assertTrue(db.insertBook("book6", "auth6", "2010-10-10")) self.assertTrue(count + 2 == self.countBook())
def insertUser(self): print("--- Insert User ---") with DatabaseUtils() as db: if(db.insertUser(self.__username, self.__name)): print("{} inserted successfully.".format(self.__username)) else: print("{} failed to be inserted.".format(self.__username))
def insertBook(self, title, author, isbn): with DatabaseUtils() as db: if (db.insertBook(title, author, isbn)): print("{} inserted successfully.".format(title)) else: print("{} failed to be inserted.".format(title)) self.listBooks()
def listBooks(self): print("--- Book ---") table = PrettyTable(['ID', 'ISBN', 'Title', 'Author']) with DatabaseUtils() as db: for book in db.getBooks(): table.add_row([book[0], book[1], book[2], book[3]]) print(table)
def createbook(): title = request.form["Title"] author = request.form["Author"] publishedDate = request.form["PublishedDate"] status = "avaliable" isbn = request.form["ISBN"] sequenceNo = 1 with DatabaseUtils() as db: for no in db.getTitle(): if no[0] == title: sequenceNo = sequenceNo + 1 headers = {"Content-type": "application/json"} data = { "Title": title, "Author": author, "PublishedDate": publishedDate, "Status": status, "ISBN": isbn, "SequenceNo": sequenceNo } response = requests.post("http://127.0.0.1:5000/book", data=json.dumps(data), headers=headers) # redirect back to home return redirect("/")
def test_getUser(self): with DatabaseUtils(self.connection) as db: results = db.get_an_user('*****@*****.**') if results == None: count = 0 else: count = 1 self.assertTrue(self.accountExists("*****@*****.**") == count)
def test_loginAccount(self): with DatabaseUtils(self.connection) as db: results = db.login_account('*****@*****.**', '123') if (results == None): count = 0 else: count = 1 self.assertTrue(self.accountExists('*****@*****.**') == count)
def insertPerson(self): print("--- Insert Person ---") name = input("Enter the person's name: ") with DatabaseUtils() as db: if (db.insertPerson(name)): print("{} inserted successfully.".format(name)) else: print("{} failed to be inserted.".format(name))
def main(self): with DatabaseUtils() as db: db.createCustomerTable() db.createCarTable() db.createBookHistoryTable() db.createExecutiveTable() print(db.getCustomer()) self.runQR()
def viewHistory(self, CustomerID): print("-----View profile------------") with DatabaseUtils() as db: for car in db.viewHistory(customerId): print("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t".format( customer[0], customer[1], customer[2], customer[3], customer[4], customer[5], customer[6], customer[7], customer[8]))
def test_validateCollection(self): with DatabaseUtils(self.connection) as db: results = db.validate_collection('1', '1') if (results == None): dbcount = 0 else: dbcount = 1 existcount = self.bookingExists('1', '1') self.assertTrue(existcount == dbcount)
def test_InsertBooking(self): with DatabaseUtils(self.connection) as db: count = self.countBookings() db.insert_booking(1, 1, '07-4-2020', '13:45', '10-4-2020', '13:45', "booked", 100) self.assertTrue(count + 1 == self.countBookings()) db.insert_booking(2, 2, '07-4-2020', '13:45', '10-4-2020', '13:45', "booked", 155) self.assertTrue(count + 2 == self.countBookings())
def deletebook(): bookid = request.form["BookID"] with DatabaseUtils() as db: for no in db.getBookState(bookid): if no[0] == "borrowed": print("can not borrow") else: response = requests.delete("http://127.0.0.1:5000/book/" + bookid) return redirect("/")
def test_deletePerson(self): with DatabaseUtils(self.connection) as db: count = self.countPeople() personID = 1 self.assertTrue(self.personExists(personID)) db.deletePerson(personID) self.assertFalse(self.personExists(personID)) self.assertTrue(count - 1 == self.countPeople())
def searchBooksISBN(self, ISBN): """ Parameters ---------- BookID : str book ISBN """ print("--- Book ---") print("{:<15} {:<15} {:<15} {:<15} {}".format("Title", "Authur", "Publish Date", "ISBN", "Status")) with DatabaseUtils() as db: for book in db.searchBooksISBN(ISBN): print("{:<15} {:<15} {:<15} {:<15} {}".format(book[1], book[2], book[3].strftime('%Y-%m-%d'), book[5], book[4]))
def menu(user): while (True): print("Welcome {}".format(user["username"])) username = str(user["username"]) password = str(user["password"]) with DatabaseUtils() as db: for cust in db.getOneCust(property, username, password): if cust[0] == "": message = "Warning!!! User Not Identified" else: message = "Autheticated!!! User Identified" print(message)
def searchCar(self, property, value): print("-----Car Searched-------------") print("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}".format( "CarID", "Status", "Name", "Model", "Brand", "Company", "Colour", "Seats", "Description", "Category", "CostPerHour", "Location", "CustID")) with DatabaseUtils() as db: for car in db.getOneCar(property, value): print("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}". format(car[0], car[1], car[2], car[3], car[4], car[5], car[6], car[7], car[8], car[9], car[10], car[11], car[12]))
def viewHistory(self, custId): print("-----View Car History------------") print("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}".format( "CarID", "Status", "Name", "Model", "Brand", "Company", "Colour", "Seats", "Description", "Category", "CostPerHour", "Location", "CustID")) with DatabaseUtils() as db: for car in db.viewHistory(custId): print("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}". format(car[0], car[1], car[2], car[3], car[4], car[5], car[6], car[7], car[8], car[9], car[10], car[11], car[12]))
def listReturnBook(self): with DatabaseUtils() as db: userId = 0 for user in db.getUser(self.__username): userId = user[0] if (userId == 0): self.insertUser() for user in db.listBooks(): userId = user[0] print("{:<15} {:<15} {:<15}".format("Title", "ISBN", "Borrowed Date")) for book in db.listReturnBooks(userId): print("{:<15} {:<15} {:<15}".format(book[0], book[1], book[2].strftime('%Y-%m-%d')))
def __init__(self, userId): self.userId = userId self.db = DatabaseUtils() while (self.isRunnig): choice = input(self.display_menu) if (choice == '1'): self.searchForBook('search') elif (choice == '2'): self.searchForBook('borrow') elif (choice == '3'): self.findBorrowedBooks() book = self.selectBook(self.borrowedBooks) if (book): self.db.returnBook(self.userId, book[0]) print("The Book was successfully returned!\n") else: print("Book selected isnt part of the list\n") elif (choice == '4'): self.isRunnig = False else: print("Invalid Choice")
def userLoginByFaceRegonition(self, username): """ Parameters ---------- username : str user name """ with DatabaseUtils() as db: inputData = (username) #then call Jun function to connect with another rasp pi loginUserData = db.searchUserData(inputData) userName = loginUserData[0] realName = loginUserData[1] + " " + loginUserData[2] print("userName: "******"realName: ", realName) socketClient(userName, realName).mainRun()
def returnBook(self, BookID): """ Parameters ---------- BookID : str book ISBN """ with DatabaseUtils() as db: userId = 0 for user in db.getUser(self.__username): userId = user[0] if (userId == 0): self.insertUser() for user in db.listBooks(): userId = user[0] id = 0 gotBook = False for book in db.getBookISBN(BookID): gotBook = True id = book[0] if (gotBook == False): print("no book record found!") else: BookBorrowedID = 0 for book in db.getReturnBook(userId, id): BookBorrowedID = book[0] cLink = book[6] if (BookBorrowedID == 0): print("no borrow book found!") else: cal = calender() rDate = cal.getReturnDate() cal.removeEvent(cLink) db.returnBook(BookBorrowedID, id, rDate)
def listBooksByAuthor(self, author): """ Search books by their author. Parameters: Author of a book Returns: All books which have been written by the author """ print("--- Books ---") table = PrettyTable(['ISBN', 'Title', 'Author']) with DatabaseUtils() as db: books = db.getBookByAuthor(author) if (len(books) > 0): for book in books: table.add_row([book[1], book[2], book[3]]) print(table) return True else: print("Book not found! please try again.") return False
def listBooksByTitle(self, title): """ Search books by book name Parameters: Book title Returns: All books with the title name """ print("--- Books ---") table = PrettyTable(['ISBN', 'Title', 'Author']) with DatabaseUtils() as db: books = db.getBookByTitle(title) if (len(books) > 0): for book in books: table.add_row([book[1], book[2], book[3]]) print(table) return True else: print("Book not found! please try again.") return False