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 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))
示例#3
0
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("/")
示例#4
0
 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))
示例#5
0
 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))
示例#6
0
 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 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 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
 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 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)
示例#13
0
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]))
示例#14
0
def main(self):
    with DatabaseUtils() as db:
        db.createCustomerTable()
        db.createCarTable()
        db.createBookHistoryTable()
        db.createExecutiveTable()
        print(db.getCustomer())
    self.runQR()
示例#15
0
 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 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())
示例#18
0
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())
示例#20
0
 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]))
示例#21
0
 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 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)
示例#23
0
 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]))
示例#24
0
    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')))                             
示例#25
0
 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()
示例#26
0
    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 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
 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 listBooksByISBN(self, isbn):
        """
        Search Books by ISBN. 
        Parameters:
            ISBN
        Returns:
            All books which have the ISBN
        """

        print("--- Books ---")
        table = PrettyTable(['ISBN', 'Title', 'Author'])
        with DatabaseUtils() as db:
            books = db.getBookByISBN(isbn)
            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
示例#30
0
    def borrowBook(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]

            gotBook = False
            status = ""
            title = ""
            id = 0

            for book in db.getBookISBN(BookID):
                gotBook = True
                status = book[4]
                title = book[1]
                id = book[0]

            if (gotBook == False):
                print("no book record found!")
            else: 
                if (status == "borrowed"):
                   print("the book is not available for borrow!")
                else:
                    cal = calender()
                    bDate = cal.getBorrowedDate()
                    cLink = cal.insertCalender(self.__username, title)
                    print(id)
                    db.borrowBook(userId, id, bDate, cLink)