def addBook(self):
     """
         Use the entered information if it is valid in order to add the
         book after the Add button is pushed.
     """
     data = [
         self.titleEdit.text(),
         self.authorEdit.text(),
         self.yearEdit.text(),
         self.genre_options.currentText(),
         self.ratingEdit.text(),
         self.copiesEdit.text(),
     ]
     invalid_data = Validations.check_all(*data)
     if invalid_data == []:
         new_book = Book(*data)
         Library.add_book(new_book)
         self.label.setText("You added the book successfully!")
     else:
         message = "Unsuccessful addition!Invalid:\n"
         message += "\n".join(invalid_data)
         self.label.setText(message)
     for gadget in self.gadgets:
         if gadget != self.genre_options:
             gadget.clear()
Example #2
0
 def test_duplicate_books(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(576.82, 'A New History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
 def test_add_book(self):
     Library(self.store, ["Fantasy"])
     Library.add_book(self.books[0])
     self.assertEqual([self.books[0]], Library.books)
     self.add_books([self.books[0], self.books[1]], Library)
     self.assertEqual([self.books[0], self.books[1]], Library.books)
     os.remove(os.path.realpath(self.store))
Example #4
0
 def test_duplicate_books(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(576.82, 'A New History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
Example #5
0
 def test_sorting(self):
     testlib = Library()
     testlib.add_book(100.32, 'First Book')
     testlib.add_book(199.3, 'Last Book')
     testlib.add_book(150, 'Middle Book')
     assert testlib.shelves[1].books[0].title == 'First Book'
     assert testlib.shelves[1].books[1].title == 'Middle Book'
     assert testlib.shelves[1].books[2].title == 'Last Book'
Example #6
0
 def test_sorting(self):
     testlib = Library()
     testlib.add_book(100.32, 'First Book')
     testlib.add_book(199.3, 'Last Book')
     testlib.add_book(150, 'Middle Book')
     assert testlib.shelves[1].books[0].title == 'First Book'
     assert testlib.shelves[1].books[1].title == 'Middle Book'
     assert testlib.shelves[1].books[2].title == 'Last Book'
 def test_number_of_different_books(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     self.assertEqual(3, Library.number_of_different_books())
     Library.add_book(self.books[0])
     self.assertEqual(3, Library.number_of_different_books())
     Library.remove_book(self.books[1])
     self.assertEqual(2, Library.number_of_different_books())
     os.remove(os.path.realpath(self.store))
Example #8
0
 def test_remove_book(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(575.01, 'An Old History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
     # remove nonexistent book
     testlib.remove_book(501.2)
     assert len(testlib.shelves[5].books) == 1
Example #9
0
 def test_remove_book(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(575.01, 'An Old History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
     # remove nonexistent book
     testlib.remove_book(501.2)
     assert len(testlib.shelves[5].books) == 1
 def test_create_genre_dict(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     Library.create_genre_dict()
     expected_dict = {"Fantasy": [self.books[1], self.books[0]],
                      "Thriller": [self.books[2]]}
     self.assertEqual(expected_dict, Library.genre_dict)
     Library.add_book(self.books[3])
     expected_dict["Thriller"].append(self.books[3])
     self.assertEqual(expected_dict, Library.genre_dict)
     os.remove(os.path.realpath(self.store))
Example #11
0
 def test_get_authors(self):
     from library import Book, Library
     tests = [Book('The Life and Lies of Albus Dumbledore', 'Rita Skeeter'),
         ('Some Other Book by Someone'),
         Book('Lab 9', 'The Best TA'),
         Book('Yet Another Book', 'Someone')]
     lib = Library()
     for test in tests:
         lib.add_book(test)
     self.assertEquals(len(lib.get_authors()), 3)
     self.assertIn('Someone', lib.get_authors())
     self.assertNotIn('', lib.get_authors())
Example #12
0
    def test_library(self):
        lib = Library()
        # check emptiness
        self.assertFalse(lib.reserve_book("user", "book", 1, 10))
        self.assertFalse(lib.check_reservation("user", "book", 5))
        self.assertFalse(lib.change_reservation("user", "book", 5, "new_user"))

        # add some users
        self.assertTrue(lib.add_user("user0"))
        self.assertFalse(lib.add_user("user0"))
        self.assertTrue(lib.add_user("user1"))
        # add some books
        lib.add_book("book0")
        lib.add_book("book0")
        lib.add_book("book1")
        lib.add_book("book2")

        # check while no reservations exist
        self.assertFalse(lib.change_reservation("user0", "book0", 5, "user1"))

        # try basic checkouts
        self.assertFalse(lib.check_reservation("user0", "book0", 5))
        self.assertTrue(lib.reserve_book("user0", "book0", 0, 10))
        self.assertTrue(lib.check_reservation("user0", "book0", 5))
        self.assertFalse(lib.check_reservation("user1", "book0", 5))
        self.assertTrue(lib.reserve_book("user1", "book0", 0, 10))
        self.assertTrue(lib.check_reservation("user1", "book0", 5))
        self.assertFalse(lib.check_reservation("user0", "book1", 5))
        self.assertTrue(lib.reserve_book("user0", "book1", 0, 10))
        self.assertTrue(lib.check_reservation("user0", "book1", 5))
        # check failure options
        self.assertFalse(lib.reserve_book("nonexistent", "book2", 0, 1))
        self.assertFalse(lib.reserve_book("user0", "no_book", 0, 1))
        self.assertFalse(lib.reserve_book("user0", "book2", 10, 0))
        self.assertFalse(lib.reserve_book("user0", "book0", 0, 1))

        # try reservation change
        self.assertTrue(lib.check_reservation("user0", "book1", 5))
        self.assertTrue(lib.change_reservation("user0", "book1", 5, "user1"))
        self.assertTrue(lib.check_reservation("user1", "book1", 5))
        self.assertFalse(lib.check_reservation("user0", "book1", 5))
        # try failure options
        self.assertFalse(
            lib.change_reservation("nonexistent", "book1", 5, "user0"))
        self.assertFalse(
            lib.change_reservation("user1", "book1", 5, "nonexistent"))
        self.assertFalse(lib.change_reservation("user1", "no book", 5,
                                                "user0"))
        self.assertFalse(lib.change_reservation("user1", "book1", 100,
                                                "user0"))
        self.assertFalse(lib.change_reservation("user1", "book1", -10,
                                                "user0"))
def main():
    lib = Library()
    lib.add_book(Book('The Life and Lies of Albus Dumbledore', 'Rita Skeeter'))

    with open('library.txt', 'r') as lib_data:
        for line in lib_data:
            lib.add_book(line)

    print(lib)
    print(lib.get_authors())
    assert len(set(lib.get_authors())) == len(lib.get_authors())
    print(lib.get_books_per_author())
    assert len(lib.get_books_per_author()) == len(lib.get_authors())
Example #14
0
class LibraryTest(unittest.TestCase):
    def setUp(self):
        self.books_by_title = {}
        self.assertEqual(self.books_by_title, {})
        self.b = Book('Django', 'Elena Santasheva')
        self.l = Library()

    def test_add_book(self):
        self.l.add_book(self.b)
        self.assertEqual(self.l.books_by_title[self.b.title], self.b)  #self.object.param

    def test_remove_book(self):
        self.l.remove_book(self.b)
        self.assertFalse('Django' in self.l.books_by_title)  # after remove_book

    def test_check_book_status(self):
        self.l.add_book(self.b)
        self.l.check_book_status(self.b.title)
        self.assertTrue(self.b.title in self.l.books_by_title)
        self.assertTrue(self.l.books_by_title[self.b.title].is_available())

    def test_borrow(self):
        self.l.add_book(self.b)
        self.l.remove_book(self.b)
        self.assertEqual(self.l.borrow('Django'), 'We do not have Django. Try something else.')

    def test_return_book(self):
        self.l.add_book(self.b)
        self.l.remove_book(self.b)
        self.assertEqual(self.l.return_book('Django'), 'We do not have Django. Try something else.')
 def test_number_of_books_by_genres(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 2, 'Thriller': 1}, actual_result)
     Library.add_book(self.books[3])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 2, 'Thriller': 2}, actual_result)
     Library.remove_book(self.books[1])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 1, 'Thriller': 2}, actual_result)
     Library.remove_book(self.books[0])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 0, 'Thriller': 2}, actual_result)
     os.remove(os.path.realpath(self.store))
Example #16
0
 def test_report_inventory(self):
     testlib = Library()
     testlib.add_book(006.74, 'Teach Yourself HTML and CSS')
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(741.5942,
                      'The Thrilling Adventures of Lovelace and Babbage')
     testlib.add_book(741.5942,
                      'The Thrilling Adventures of Lovelace and Babbage')
     out = StringIO()
     report = "The books in this library are:\n"
     report += "6.74 - Teach Yourself HTML and CSS\n"
     report += "576.82 - A New History of Life\n"
     report += "741.5942 - The Thrilling Adventures of Lovelace and Babbage\n"
     report += "741.5942 - The Thrilling Adventures of Lovelace and Babbage\n"
     testlib.report_inventory(out)
     assert out.getvalue() == report
Example #17
0
 def test_add_book(self):
     testlib = Library()
     testlib.add_book(006.74, 'Teach Yourself HTML and CSS')
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(741.5942, 'The Thrilling Adventures of Lovelace and Babbage')
     assert testlib.shelves[0].books[0].dewey == 006.74
     assert testlib.shelves[0].books[0].title == 'Teach Yourself HTML and CSS'
     assert testlib.shelves[5].books[0].dewey == 576.82
     assert testlib.shelves[5].books[0].title == 'A New History of Life'
     assert testlib.shelves[7].books[0].title == 'The Thrilling Adventures of Lovelace and Babbage'
Example #18
0
 def test_add_book(self):
     testlib = Library()
     testlib.add_book(006.74, 'Teach Yourself HTML and CSS')
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(741.5942,
                      'The Thrilling Adventures of Lovelace and Babbage')
     assert testlib.shelves[0].books[0].dewey == 006.74
     assert testlib.shelves[0].books[
         0].title == 'Teach Yourself HTML and CSS'
     assert testlib.shelves[5].books[0].dewey == 576.82
     assert testlib.shelves[5].books[0].title == 'A New History of Life'
     assert testlib.shelves[7].books[
         0].title == 'The Thrilling Adventures of Lovelace and Babbage'
Example #19
0
 def test_report_inventory(self):
     testlib = Library()
     testlib.add_book(006.74, 'Teach Yourself HTML and CSS')
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(741.5942, 'The Thrilling Adventures of Lovelace and Babbage')
     testlib.add_book(741.5942, 'The Thrilling Adventures of Lovelace and Babbage')
     out = StringIO()
     report = "The books in this library are:\n"
     report += "6.74 - Teach Yourself HTML and CSS\n"
     report += "576.82 - A New History of Life\n"
     report += "741.5942 - The Thrilling Adventures of Lovelace and Babbage\n"
     report += "741.5942 - The Thrilling Adventures of Lovelace and Babbage\n"
     testlib.report_inventory(out)
     assert out.getvalue() == report
Example #20
0
class TestLibrary():

    def setup(self):
        self.books_by_title = {}
        assert self.books_by_title == {}
        self.b = Book('Django', 'Elena Santasheva')
        self.l = Library()

    @pytest.mark.LibraryTest
    def test_add_book(self):
        self.l.add_book(self.b)
        assert self.l.books_by_title[self.b.title] == self.b  #self.object.param

    @pytest.mark.LibraryTest
    def test_remove_book(self):
        self.l.remove_book(self.b)
        assert 'Django' not in self.l.books_by_title  # after remove_book

    @pytest.mark.LibraryTest
    def test_check_book_status(self):
        self.l.add_book(self.b)
        self.l.check_book_status(self.b.title)
        assert self.b.title in self.l.books_by_title
        assert self.l.books_by_title[self.b.title].is_available() is True

    @pytest.mark.LibraryTest
    def test_borrow(self):
        self.l.add_book(self.b)
        self.l.remove_book(self.b)
        assert self.l.borrow('Django') == 'We do not have Django. Try something else.'

    @pytest.mark.LibraryTest
    def test_return_book(self):
        self.l.add_book(self.b)
        self.l.remove_book(self.b)
        assert self.l.return_book('Django') == 'We do not have Django. Try something else.'
Example #21
0
  def put(self):
    params = decode(self.request.body)

    Library.add_book(self, params["name"], params["qtd"])
Example #22
0
class HumanComputerInteract:
    def __init__(self):
        self.lib_set = set()
        self.lib = None
        self.load_cache()
        print("*******************************************************")
        print("* 欢迎使用仙得法歌图书管理系统!")
        print("* 开始创建和管理自己的图书馆吧!(*^_^*) !")
        print("* ps:系统有待完善,添加书籍时,请一定保证书名和ISBN的唯一性")
        print("*******************************************************\n")
        self.print_lib_set()

    def run(self):
        print("你可以选择新建一个图书馆或者打开\\移除一个已存在的图书馆:"
              "\n# 输入1:新建\n# 输入2:打开\n# 输入3:重开\n# 输入4:移除\n# 其它:退出系统")
        a = input(">>>").strip()
        if a == "1":
            # 创建图书馆
            self.creat_lib()
            while True:
                self.print_options()
                self.lib_operation()
        elif a == "2":
            # 打开图书馆
            self.open_lib()
            while True:
                self.print_options()
                self.lib_operation()
        elif a == "3":
            self.save_lib()
            self.__init__()
            self.run()
        elif a == "4":
            self.remove_lib()
            self.run()
        else:
            # self.save_lib()
            self.exit()

    def creat_lib(self):
        lib_name = input("请输入新建的图书馆的名字:").strip()
        flag = None
        while True:
            if lib_name in self.lib_set:
                print(lib_name + "已存在!")
                print("是否打开" + lib_name + ":\n# yes:打开\n# no:返回\n# 其他:退出系统")
                flag = input(">>>").strip()
                if flag == "yes":
                    break
                elif flag == "no":
                    break
                else:
                    self.exit()
            else:
                break
        if flag == "yes":
            self.lib = Library(lib_name)
            print("成功打开" + lib_name + "!")
            while True:
                self.print_options()
                self.lib_operation()
        elif flag == "no":
            self.run()
        else:
            lib_location = input("请输入" + lib_name + "的地址:").strip()
            default_return_book_position = input("请输入" + lib_name +
                                                 "的默认还书地点:").strip()
            max_borrow_time_limit = int(
                input("请输入" + lib_name + "的书籍最大借阅期限(天):").strip())
            self.lib = Library(lib_name, lib_location,
                               default_return_book_position,
                               max_borrow_time_limit)
            self.lib_set.add(lib_name)
            print("成功创建" + lib_name + "!")

    def open_lib(self):
        lib_name = input("请输入你想打开的图书馆的名字:").strip()
        flag = None
        while True:
            if lib_name not in self.lib_set:
                print(lib_name + "不存在!")
                print("是否继续打开图书馆:\n# yes:继续\n# no:返回\n# 其他:退出系统")
                flag = input(">>>").strip()
                if flag == "yes":
                    lib_name = input("请输入你想打开的图书馆的名字:").strip()
                elif flag == "no":
                    break
                else:
                    self.exit()
            else:
                break
        if flag == "no":
            self.run()
        else:
            self.lib = Library(lib_name)
            print("成功打开" + lib_name + "!")

    def save_lib(self):
        print("是否保存本次操作:\n# yes:保存\n# no:不保存\n# 其他:退出系统")
        flag = input(">>>").strip()
        if flag == "yes":
            self.lib.save_cache()
            print("成功保存本次操作!")
        elif flag == "no":
            pass
        else:
            self.exit()

    def exit(self):
        try:
            self.save_cache()
            sys.exit(0)
        finally:
            print("已保存记录!")
            print("已成功退出系统!")
            print("欢迎下次使用仙得法歌图书管理系统!")

    def load_cache(self):
        if not os.path.exists(LIB_SET_CACHE_PATH):
            f = open(LIB_SET_CACHE_PATH, 'wb')
            lib_set = set()
            pickle.dump(lib_set, f)
            f.close()
        f = open(LIB_SET_CACHE_PATH, 'rb')
        try:
            self.lib_set = pickle.load(f)
        except ValueError:
            self.reset_cache()
        f.close()

    def save_cache(self):
        f = open(LIB_SET_CACHE_PATH, 'wb')
        pickle.dump(self.lib_set, f)
        f.close()

    def reset_cache(self):
        f = open(LIB_SET_CACHE_PATH, 'wb')
        lib_set = set()
        pickle.dump(lib_set, f)
        f.close()
        self.load_cache()

    def remove_lib(self):
        lib_name = input("请输入你想要移除的图书馆:").strip()

        if lib_name in self.lib_set:
            file = "lib/" + lib_name + "_cache.pkl"
            if os.path.exists(file):
                os.remove(file)
            file = "lib/" + lib_name + "_barcode_no.pkl"
            if os.path.exists(file):
                os.remove(file)
            self.lib_set.discard(lib_name)
            print("成功移除" + lib_name + "!")
        else:
            print(lib_name + "不存在!")

    def print_lib_set(self):
        print("***********************************************")
        print("已存在的图书馆:")
        print("-----------------------------------------------")
        for lib_name in self.lib_set:
            lib = Library(lib_name)
            lib.print_library_info()
        print("***********************************************")

    def print_options(self):
        print("选项:\n"
              "# 1:添加书籍\n"
              "# 2:精确匹配查询书籍\n"
              "# 3:模糊匹配查询书籍\n"
              "# 4:删除书籍\n"
              "# 5:借阅书籍\n"
              "# 6:归还书籍\n"
              "# 7:查询借阅记录\n"
              "# 8:借阅分布\n"
              "# 9:馆藏目录\n"
              "# 10:当前借阅\n"
              "# 11:借还日志\n"
              "# 12:重开\n"
              "# ?:关于" + self.lib.name + "\n"
              "# 其它:退出系统")

    def lib_operation(self):
        b = input(">>>").strip()
        if b == "1":
            self.add_book()
            while True:
                flag = input(
                    "是否继续添加书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.add_book()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "2":
            self.exact_query_system()
            while True:
                flag = input(
                    "是否继续查询书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.exact_query_system()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "3":
            self.fuzzy_query_system()
            while True:
                flag = input(
                    "是否继续查询书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.fuzzy_query_system()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "4":
            self.exact_remove_system()
            while True:
                flag = input(
                    "是否继续删除书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.exact_remove_system()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "5":
            self.loan_system()
            while True:
                flag = input(
                    "是否继续借阅书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.loan_system()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "6":
            self.return_system()
            while True:
                flag = input(
                    "是否继续归还书籍:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.loan_system()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "7":
            self.query_loan_record()
            while True:
                flag = input(
                    "是否继续查询借阅记录:\n# yes:继续\n# no:返回\n# 其他:退出系统\n>>>").strip()
                if flag == "yes":
                    self.query_loan_record()
                elif flag == "no":
                    break
                else:
                    self.save_lib()
                    self.exit()
        elif b == "8":
            self.lib.borrow_statistics()
        elif b == "9":
            self.lib.print_collection_index()
        elif b == "10":
            self.lib.print_borrow_system()
        elif b == "11":
            self.lib.print_borrow_return_log()
        elif b == "12":
            self.save_lib()
            self.__init__()
            self.run()
        elif b == "?" or b == "?":
            self.lib.print_library_info()
        else:
            self.save_lib()
            self.exit()

    def add_book(self):
        book_title = input("书籍名称:").strip()
        book_author = input("作者:").strip()
        book_isbn = input("ISBN:").strip()
        book_price = float(input("定价:").strip())
        book_translator = input("译者【没有使用enter跳过】:").strip()
        book_campus_location = input("馆藏地点:").strip()
        book_call_no = input("索书号:").strip()
        book_number = int(input("册数:").strip())
        book = Book(book_title,
                    book_author,
                    book_isbn,
                    book_price,
                    translator=book_translator if book_translator else None)
        self.lib.add_book(book, book_campus_location, book_call_no,
                          book_number)

    def exact_query_system(self):
        way = input("请输入精确匹配查询方式【可选:title/ISBN】:").strip()
        while True:
            if way not in {"title", "ISBN"}:
                print("error:输入不符合要求,请重新输入!")
                way = input("请输入精确匹配查询方式【可选:title/ISBN】:").strip()
            else:
                break
        if way == "title":
            keywords = [
                x for x in (
                    input("请输入需要查询的书籍名【可输入多个,以空格分隔】\n>>>").strip()).split()
            ]
        if way == "ISBN":
            keywords = [
                x for x in (input("请输入需要查询的书籍的ISBN【可输入多个,以空格分隔】\n>>>").strip()
                            ).split()
            ]
        self.lib.exact_match_query_book(way, keywords)

    def fuzzy_query_system(self):
        way = input("请输入模糊匹配查询方式【可选:title/ISBN】:").strip()
        while True:
            if way not in {"title", "ISBN"}:
                print("error:输入不符合要求,请重新输入!")
                way = input("请输入精确匹配查询方式【可选:title/ISBN】:").strip()
            else:
                break
        if way == "title":
            keywords = [
                x for x in (
                    input("请输入需要查询的书籍名关键词【可输入多个,以空格分隔】\n>>>").strip()).split()
            ]
        if way == "ISBN":
            keywords = [
                x for x in (input(
                    "请输入需要查询的书籍的ISBN关键数字【可输入多个,以空格分隔】\n>>>").strip()).split()
            ]
        self.lib.fuzzy_query_book(way, keywords)

    def exact_remove_system(self):
        way = input("请输入删除方式【可选:title/ISBN】:").strip()
        while True:
            if way not in {"title", "ISBN"}:
                print("error:输入不符合要求,请重新输入!")
                way = input("请输入删除方式【可选:title/ISBN】:").strip()
            else:
                break
        if way == "title":
            keywords = [
                x for x in input(
                    "请输入需要删除的书籍名【可输入多个,以空格分隔】\n>>>").strip().split()
            ]
        if way == "ISBN":
            keywords = [
                x for x in input(
                    "请输入需要删除的书籍的ISBN【可输入多个,以空格分隔】\n>>>").strip().split()
            ]
        self.lib.exact_match_remove_book(way, keywords)

    def loan_system(self):
        person = input("请输入借阅人的姓名:").strip()
        keywords = [
            x for x in input("请输入需要借阅的书籍名【可输入多个,以空格分隔】\n>>>").strip().split()
        ]
        self.lib.borrow_manage(keywords, person)

    def return_system(self):
        barcodes = [
            x
            for x in input("请输入需要归还的书籍条码号【可输入多个,以空格分隔】\n>>>").strip().split()
        ]
        self.lib.return_manage(barcodes)

    def query_loan_record(self):
        way = input("请输入查询借阅记录的方式【可选:borrower/title/date】:").strip()
        while True:
            if way not in {"borrower", "title", "date"}:
                print("error:输入不符合要求,请重新输入!")
                way = input("请输入查询借阅记录的方式【可选:borrower/title/date】:").strip()
            else:
                break
        if way == "borrower":
            keyword = input("请输入需要查询借阅记录的借阅人:\n>>>").strip()
        if way == "title":
            keyword = input("请输入需要查询借阅记录的书籍名:\n>>>").strip()
        if way == "date":
            keyword = input("请输入需要查询借阅记录的日期:\n>>>").strip()
        self.lib.borrow_query(way, keyword)
Example #23
0
from book import Book
from library import Library

nss_library = Library("NSS Library")
print(nss_library.name)

# creating an instance (which is an object) of the Book class so they will all have the same attributes and methods. To create an instance of the class, you type the name of the class and put parenthesis after it. You should always store the object instance in a variable.
book_one = Book("J. K. Rowling", "Harry Potter and the Philosopher's Stone")
# book_one.title = "Harry Potter and the Philosopher's Stone"
# book_one.author = "J. K. Rowling"
book_one.current_page = 1

print(f"I am reading {book_one.title} by {book_one. author}")

# book_two = dict()

book_one.start_reading()

# book_two = Book()
# book_two.title = "Harry Potter and the Chamber of Secrets"
# book_two.author = "J. K. Rowling"
# book_two.current_page = 197

# book_two.start_reading()
# Each instance is an object

nss_library.add_book(book_one)


nss_library.set_address("301 Plus Park Blvd.")
print(nss_library.address)
class Menu:
    def __init__(self):
        self.lib = Library()
        self.selected_book = Book("", "", "", "")
        self.options = {
            "1": self.add_book,
            "2": self.display_all,
            "3": self.display_current,
            "4": self.select_book,
            "5": self.deselect_book,
            "6": self.search,
            "7": self.modify_selected,
            "99": self.display_menu,
            "0": self.exit
        }
        self.test_case()

    def test_case(self):
        self.lib.add_book("Peter", "Robinson", "Action", "5")
        self.lib.add_book("John Doe", "Peter Jake", "Adventure", "3")
        self.lib.add_book("Orange John", "LoL", "Action", "3")

    #method get_input()
    def get_input(self):
        return raw_input("> ")

    #method display_menu()
    def display_menu(self):
        print("""
Welcome to your digital console library!
Please type one of the following:

1. Add a new book
2. Display all read books
3. Display currently selected book
4. Select a book using an ID
5. Deselect currently selected book
6. Search for specific books
7. Modify selected book


99. Display these options
0. Exit
        """)

    #method display_search_options()
    def display_search(self):
        print("""
How would you like to search for your book?:

1. By name
2. By author
3. By category
4. By rating
5. By id

0. Exit
        """)

    #method beautify(func)
    def beautify(self, func):
        print("*=========*")
        func()
        print("*=========*")

    #method run()
    def run(self):
        self.beautify(self.display_menu)

        is_running = True

        while is_running:
            option = str(self.get_input())
            action = self.options.get(option)
            if action != None:
                action()
            else:
                print("\"{0}\" is not a valid option. Please try again")

    #method add_book()
    def add_book(self):
        print("""
To add a book, type \"name, author, category, rating\"
To quit, type \"0\"
        """)
        is_adding = True
        while is_adding:
            param_arr = str(self.get_input()).strip().split(",")
            if len(param_arr) == 4:
                self.lib.add_book(param_arr[0], param_arr[1], param_arr[2],
                                  param_arr[3])
                print("Book \"{0}\" was added!".format(param_arr[0]))
            elif len(param_arr) == 1:
                if param_arr[0] == "0":
                    print("Exiting...")
                    is_adding = False
                else:
                    print("Invalid parameters were given.")
            else:
                print("Not enough parameters were given.")

    #method display_all()
    def display_all(self):
        if len(self.lib.books) > 0:
            for b in self.lib.books:
                self.beautify(b.show_info)
        else:
            print("Currently, you have no books read.")

    #method display_current()
    def display_current(self):
        if self.selected_book != None:
            self.beautify(self.selected_book.show_info)
        else:
            print("No book has been selected.")

    #method select_book()
    def select_book(self):
        is_selecting = True

        while is_selecting:
            print("""
Please enter an ID of a book you wish to select!
Type \"-1\" to leave.
            """)
            try:
                b_id = int(self.get_input())
                if b_id != "-1":
                    book_arr = self.lib.search(book_id=b_id)
                    if len(book_arr) == 1:
                        self.selected_book = book_arr[0]

                    if self.selected_book == None:
                        print("No book was selected")
                    else:
                        print("Selected book...")
                        self.beautify(self.selected_book.show_info)

                print("Exiting...")
                is_selecting = False
            except ValueError:
                print("\"{0}\" was not a valid ID. Please try again.".format(
                    b_id))

    #method deselect_book()
    def deselect_book(self):
        if self.selected_book != None:
            self.selected_book = None
            print("\"{0}\" book has been deselected".format(
                self.selected_book.name))
        else:
            print("No book was currently selected")

    #method search()
    def search(self):
        self.beautify(self.display_search)

        is_searching = True

        while is_searching:
            try:
                option = int(self.get_input())
                name = author = category = rating = b_id = None
                if option == 1:
                    print("Please enter a name.")
                    name = str(self.get_input())
                elif option == 2:
                    print("Please enter an author.")
                    author = str(self.get_input())
                elif option == 3:
                    print("Please enter a category.")
                    category = str(self.get_input())
                elif option == 4:
                    print("Please enter a rating.")
                    rating = str(self.get_input())
                elif option == 5:
                    print("Please enter an ID.")
                    b_id = str(self.get_input())
                elif option == 0:
                    print("Exiting search...")
                    is_searching = False
                else:
                    raise ValueError(
                        "\"{0}\" was not a valid option!".format(option))

                book_arr = self.lib.search(name=name,
                                           author=author,
                                           category=category,
                                           rating=rating,
                                           book_id=b_id)
                if len(book_arr) > 0:
                    for b in book_arr:
                        self.beautify(b.show_info)
                else:
                    print("You have currently no books read. Keep reading!")

                is_searching = False
            except ValueError as error:
                print(repr(error))

    #method modify_selected()
    def modify_selected(self):
        if self.selected_book != None:
            is_modifying = True
            print("""
To modify a book, type \"name, author, category, rating\"
If there's a parameter you wish to not edit, type \"none\" to keep it
To exit, type \"0\"
            """)
            while is_modifying:
                param_arr = str(self.get_input()).split(",")
                if len(param_arr) == 4:
                    self.lib.modify_book(param_arr[0], param_arr[1],
                                         param_arr[2], param_arr[3])
                elif len(param_arr) == 1:
                    print("Exiting...")
                    is_modifying = False
                else:
                    print("Not enough parameters were passed.")
        else:
            print("No book was selected for modification.")

    #methods exit()
    def exit(self):
        print("Keep on reading!")
        sys.exit(0)
Example #25
0
print(customer1.display_customer_details() == "Michael Neiman")
"""
1. add/remove_book methods recieve only objects of type Book - TODO.
"""
"""
2. add/remove_customer methods recieve only objects of type Customer - TODO.
"""
"""
3. borrow/retrieve/recommend methods recieve only objects of type Book and Customer - TODO.
"""
"""
4. Exceeding the maximal amount of customers/books in library.
"""
library1 = Library(0, 0, 0)
print(
    library1.add_book(book1) ==
    "Library at maximal capacity. You cannot add any more books.")
print(
    library1.add_customer(customer1) ==
    "Library at maximal capacity. You cannot add any more customers.")
print(library1.remove_book(book1) == "Inventory empty.")
print(library1.remove_customer(customer1) == "Customer database empty.")
"""
5. Adding/removing books/customers.
"""
library2 = Library(1, 1, 0)
library2.add_book(book1)
print(len(library2.books) == 1)
library2.remove_book(book1)
print(len(library2.books) == 0)
library2.add_customer(customer1)
Example #26
0
class TestLibrary(TestCase):
    def setUp(self):
        MockReservation._ids = count(0)
        self.lib = Library()
        self.lib._users.add('person1')
        self.lib._users.add('person2')
        self.lib._users.add('person3')
        self.lib._books['book1'] = 1
        self.lib._books['book2'] = 2
        self.lib._books['book3'] = 3
        self.lib.reserve_book('person1', 'book1', 0, 2, MockReservation)
        self.lib.reserve_book('person2', 'book2', 0, 3, MockReservation)
        self.lib.reserve_book('person3', 'book2', 1, 3, MockReservation)
        self.lib.reserve_book('person1', 'book3', 4, 5, MockReservation)
        self.lib.reserve_book('person3', 'book3', 4, 7, MockReservation)

    def test_add_user_same(self):
        self.assertFalse(self.lib.add_user('person1'))

    def test_add_user_different(self):
        self.assertTrue(self.lib.add_user('person4'))

    def test_add_book_same(self):
        self.lib.add_book('book1')
        self.assertEqual(self.lib._books['book1'], 2)
        self.lib.add_book('book2')
        self.assertEqual(self.lib._books['book2'], 3)
        self.lib.add_book('book3')
        self.assertEqual(self.lib._books['book3'], 4)

    def test_add_book_different(self):
        self.lib.add_book('book4')
        self.assertEqual(self.lib._books['book4'], 1)

    def test_reserve_book_wrong_user(self):
        self.assertEqual(
            self.lib.reserve_book('person4', 'book1', 0, 2, MockReservation),
            (False, 'wronguser'))
        self.assertEqual(
            self.lib.reserve_book('person5', 'book2', 3, 3, MockReservation),
            (False, 'wronguser'))

    def test_reserve_book_wrong_date_format(self):
        self.assertEqual(
            self.lib.reserve_book('person1', 'book1', 2, 1, MockReservation),
            (False, 'wrongdate'))
        self.assertEqual(
            self.lib.reserve_book('person2', 'book2', 3, 1, MockReservation),
            (False, 'wrongdate'))

    def test_reserve_book_wrong_book(self):
        self.assertEqual(
            self.lib.reserve_book('person1', 'book4', 0, 2, MockReservation),
            (False, 'wrongbook'))
        self.assertEqual(
            self.lib.reserve_book('person2', 'book5', 0, 2, MockReservation),
            (False, 'wrongbook'))

    def test_reserve_book_not_enough_books(self):
        self.assertEqual(
            self.lib.reserve_book('person2', 'book1', 1, 2, MockReservation),
            (False, 'nobook'))
        self.assertEqual(
            self.lib.reserve_book('person1', 'book2', 3, 3, MockReservation),
            (False, 'nobook'))

    def test_reserve_book_correct(self):
        self.assertEqual(
            self.lib.reserve_book('person1', 'book1', 3, 8, MockReservation),
            (True, 5))
        self.assertEqual(
            self.lib.reserve_book('person2', 'book3', 3, 6, MockReservation),
            (True, 6))
        self.assertEqual(
            self.lib.reserve_book('person1', 'book3', 6, 7, MockReservation),
            (True, 7))
        self.assertEqual(
            self.lib.reserve_book('person3', 'book2', 0, 0, MockReservation),
            (True, 8))

    def test_check_reservation_doesnt_exist_wrong_user(self):
        self.assertFalse(self.lib.check_reservation('person1', 'book2', 1))
        self.assertFalse(self.lib.check_reservation('person2', 'book3', 5))

    def test_check_reservation_doesnt_exist_wrong_book(self):
        self.assertFalse(self.lib.check_reservation('person1', 'book3', 1))
        self.assertFalse(self.lib.check_reservation('person3', 'book2', 4))

    def test_check_reservation_doesnt_exist_wrong_date(self):
        self.assertFalse(self.lib.check_reservation('person1', 'book1', 3))
        self.assertFalse(self.lib.check_reservation('person3', 'book2', 0))

    def test_check_reservation_exists(self):
        self.assertTrue(self.lib.check_reservation('person1', 'book1', 0))
        self.assertTrue(self.lib.check_reservation('person2', 'book2', 2))
        self.assertTrue(self.lib.check_reservation('person3', 'book3', 7))

    def test_change_reservation_wrong_new_user(self):
        self.assertFalse(
            self.lib.change_reservation('person1', 'book1', 1, 'person4'))
        self.assertFalse(
            self.lib.change_reservation('person2', 'book2', 1, 'person5'))

    def test_change_reservation_wrong_user_in_reservation(self):
        self.assertFalse(
            self.lib.change_reservation('person1', 'book2', 1, 'person2'))
        self.assertFalse(
            self.lib.change_reservation('person2', 'book3', 5, 'person3'))

    def test_change_reservation_wrong_book_in_reservation(self):
        self.assertFalse(
            self.lib.change_reservation('person1', 'book3', 1, 'person2'))
        self.assertFalse(
            self.lib.change_reservation('person3', 'book2', 4, 'person2'))

    def test_change_reservation_wrong_date_in_reservation(self):
        self.assertFalse(
            self.lib.change_reservation('person1', 'book1', 3, 'person3'))
        self.assertFalse(
            self.lib.change_reservation('person3', 'book2', 0, 'person1'))

    def test_change_reservation_correct(self):
        self.assertTrue(
            self.lib.change_reservation('person1', 'book1', 0, 'person2'))
        self.assertTrue(
            self.lib.change_reservation('person2', 'book2', 2, 'person1'))
        self.assertTrue(
            self.lib.change_reservation('person3', 'book3', 7, 'person1'))
Example #27
0
from book import Book
from reader import Reader
from library import Library
from book_list import books_list

if __name__ == '__main__':
    #We open the library, for now it does not have any book
    # Nous ouvrons la bibliothèque, pour l'instant elle n'a pas de livre
    library = Library()

    # For each book data in the list, we instanciate a book object and add it to the library
    # Pour chaque donnée livre de la liste, nous instancions un objet livre et nous l'ajoutons à la bibliothèque.
    for book in books_list:
        book = Book(title=book[0], pages=book[1])
        library.add_book(book)

    # A new reader come in the library
    reader = Reader()
    # He wants to borrow a book but this one does not exists so an exception shows up
    # Il veut emprunter un livre mais celui-ci n’existant pas, une exception se présente
    reader.borrow_book(library, 'test')
    # Instead he borrows Harry Potter (OK it is not a title but let's keep things simple)
    # Au lieu de cela, il emprunte Harry Potter (OK, ce n'est pas un titre, mais gardons les choses simples)
    reader.borrow_book(library, 'Harry Poter')
    # Then he read the whole book
    # Puis il a lu le livre en entier
    reader.read_book()
Example #28
0
class ConsoleApp:
    def __init__(self):
        self._library = Library()
        self._users = []
        self._users.append(User("admin", "42"))
        self._current_user = None

    def change_user(self):
        name = input("Enter user name.")
        if User(name) not in self._users:
            char = input("There is no user like that! Wanna add user? [+/-]\t")
            if char == "+":
                password = input(
                    "Enter a password or - if there is no password for user.\t"
                )
                if password == "-":
                    password = None
                self._users.append(User(name, password))
                self._current_user = self._users[-1].name
            else:
                print(
                    "Can't find this user, so it's impossible to change current user."
                )
                return
        else:
            password = input("Enter a password or - if it doesn't exist,\t")
            if password == "-":
                password = None
            if not self.find_user_by_name(name).validation(password):
                print("Error. Incorrect password.")
                return
            self._current_user = name

    def adding_book_menu(self, name=None, author=None):
        if not name:
            name = input("Enter a name.\t")
            author = input("Enter an author.\t")
        else:
            print("Name - " + name)
            print("Author - " + author)
        try:
            year = int(input("Enter a year or 0 if unknown.\t"))
        except ValueError:
            print("Not valid year.")
            exit(1)
        description = input("Enter a description or - of unknown.\t")
        if description == "-":
            description = None
        if not self._library.add_book(name, author, year, description):
            print("This book already exists!")
        char = "+"
        while char == "+":
            char = input("Wanna add tags? \t")
            if char == "+":
                tag = input("Enter a tag. \t")
                self.library.book_list[-1].add_tag(tag)
        char = "+"
        while char == "+":
            char = input("Wanna add genres? \t")
            if char == "+":
                genre = input("Enter a genre. \t")
                self.library.book_list[-1].add_genre(genre)
        if not self._library.search_author(author):
            answer = input("Wanna add an author? [+/-]\t")
            if answer == "+":
                self.adding_author_menu(author)

    def adding_author_menu(self, name=None):
        if not name:
            name = input("Enter a name.\t")
        else:
            print("Name - " + name)
        try:
            birth_year = int(input("Enter a year of birth or 0 if unknown.\t"))
        except ValueError:
            print("Not valid year.")
            exit(1)
        try:
            death_year = int(input("Enter a year of death or 0 if unknown.\t"))
        except ValueError:
            print("Not valid year.")
            exit(1)
        description = input("Enter a description or - of unknown.\t")
        if description == "-":
            description = None
        if not self._library.add_author(name, birth_year, death_year,
                                        description):
            print("This author already exists.")
            return
        char = "+"
        while char == "+":
            char = input("Wanna add genres? \t")
            if char == "+":
                genre = input("Enter a genre. \t")
                self.library.author_list[-1].add_genre(genre)
        char = "+"
        while char == "+":
            char = input("Wanna add books? \t")
            if char == "+":
                book = input("Enter a book. \t")
                self._library.author_list[-1].add_book(book)
                if not self._library.search_book(book):
                    answer = input(
                        "Wanna add this book to the library? [+/-] \t")
                    if answer == "+":
                        self.adding_book_menu(book, name)

    def deleting_book_menu(self):
        if self.find_user_by_name(self._current_user).moderation:
            name = input("Enter a name.\t")
            if not self._library.delete_book(name):
                print("There is no book with that name.")
        else:
            print("You have no rights to do it. Change the user first.")

    def deleting_author_menu(self):
        if self.find_user_by_name(self._current_user).moderation:
            name = input("Enter a name.\t")
            if not self._library.delete_author(name):
                print("There is no author with that name.")
        else:
            print("You have no rights to do it. Change the user first.")

    def editing_book_menu(self):
        if self.find_user_by_name(self._current_user).moderation:
            name = input("Enter a name.\t")
            author = input("Enter an author.\t")
            try:
                year = int(input("Enter a year or 0 if unknown.\t"))
            except ValueError:
                print("Not valid year.")
                exit(1)
            description = input("Enter a description or - of unknown.\t")
            if description == "-":
                description = None
            if not self._library.edit_book(name, author, year, description):
                char = input(
                    "This book does not exist. Wanna add this book? [+/-]\t")
                if char == "+":
                    self._library.add_book(name, author, year, description)
        else:
            print("You have no rights to do it. Change the user first.")

    def editing_author_menu(self):
        if self.find_user_by_name(self._current_user).moderation:
            name = input("Enter a name.\t")
            try:
                birth_year = int(
                    input("Enter a year of birth or 0 if unknown.\t"))
            except ValueError:
                print("Not valid year.")
                exit(1)
            try:
                death_year = int(
                    input("Enter a year of death or 0 if unknown.\t"))
            except ValueError:
                print("Not valid year.")
                exit(1)
            description = input("Enter a description or - of unknown.\t")
            if description == "-":
                description = None
            if not self._library.edit_author(name, birth_year, death_year,
                                             description):
                char = input(
                    "This author does not exist. Wanna add this author? [+/-]\t"
                )
                if char == "+":
                    self._library.add_author(name, birth_year, death_year,
                                             description)
        else:
            print("You have no rights to do it. Change the user first.")

    def book_info_menu(self):
        name = input("Enter a name.\t")
        self._library.get_info_about_book(name)

    def author_info_menu(self):
        name = input("Enter a name.\t")
        self._library.get_info_about_author(name)

    def tag_searching_menu(self):
        tag = input("Enter a tag.\t")
        this_book_list = self.library.search_by_tag(tag)
        print("Books with this tag:")
        if not len(this_book_list):
            print("There is no books with this tag.")
        for books in this_book_list:
            print(books.name + ", " + books.author)

    def genre_searching_menu(self):
        genre = input("Enter a genre.\t")
        this_book_list, this_author_list = self.library.search_by_genre(genre)
        print("Books with this genre:")
        if not len(this_book_list):
            print("There is no books with this genre.")
        for books in this_book_list:
            print(books.name + ", " + books.author)
        print("Authors associated with this genre:")
        if not len(this_author_list):
            print("There is no authors associated with this genre.")
        for authors in this_author_list:
            print(authors.name)

    def find_user_by_name(self, name):
        for user in self._users:
            if user.name == name:
                return user
        return None

    def add_favourite_tags(self):
        tag = input("Enter a tag.\t")
        if self._current_user != "admin":
            self.find_user_by_name(self._current_user).add_tags(tag)
        else:
            print("Forbidden operation - admin can't do it.")

    def add_favourite_genres(self):
        genre = input("Enter a genre.\t")
        if self._current_user != "admin":
            self.find_user_by_name(self._current_user).add_genres(genre)
        else:
            print("Forbidden operation - admin can't do it.")

    def add_favourite_authors(self):
        author = input("Enter a genre.\t")
        if self._current_user != "admin":
            self.find_user_by_name(self._current_user).add_authors(author)
        else:
            print("Forbidden operation - admin can't do it.")

    def add_favourite_books(self):
        book = input("Enter a name of the book.\t")
        author = input("Enter a name of the author.\t")
        if self._current_user != "admin":
            self.find_user_by_name(self._current_user).add_books(book, author)
        else:
            print("Forbidden operation - admin can't do it.")
        if not self._library.search_book(book):
            char = input(
                "This book does not exist. Wanna add this book? [+/-]\t")
            if char == "+":
                self.adding_book_menu(book, author)

    def delete_user(self):
        name = input("Enter a name of the user.\t")
        if name != "admin":
            password = input("Enter a password or - if it doesn't exist,\t")
            if password == "-":
                password = None
            if not self.find_user_by_name(name).validation(password):
                print("Error. There is no user like this.")
                return
            self._users.remove(User(name, password))

    def user_preferences(self):
        print(self.find_user_by_name(self._current_user))

    def change_user_status(self):
        if self.find_user_by_name(self._current_user).moderation:
            name = input("Enter a name.\t")
            if not self.find_user_by_name(name):
                print("There is no user with this name!")
                return
            print("Current status: moderation rights  - " +
                  str(self.find_user_by_name(name).moderation))
            char = input("Wanna change? [+/-]\t")
            if char == "+":
                self.find_user_by_name(
                    name
                ).moderation = not self.find_user_by_name(name).moderation
        else:
            print("Current user have no rights to change status.")

    @property
    def library(self):
        return self._library
Example #29
0
            max_scan_days = int(line_array[2])

        # second line
        elif (counter == 1):
            book_scores = list(map(int, line_array))

        # desc of lib
        elif (counter != 0 and counter != 1 and counter % 2 == 0):
            lib_id += 1
            current_library = Library(lib_id, line_array[0], line_array[1],
                                      line_array[2])

        # contents of lib
        elif (counter != 0 and counter != 1 and counter % 2 == 1):
            for book in line_array:
                current_library.add_book(Book(book))

            libraries.append(current_library)

        counter = counter + 1

# libraries
# num_of_books
# num_of_libs
# max_scan_days
# book_scores

comp_signuptime = sys.maxsize
lib = None
days_needed = 0
num_of_lib_to_scan = 0
Example #30
0
while True:
    match choice(customer.name):
        case 1:
            cls()
            library.display_available_books()
            final()
        case 2:
            cls()
            if customer.is_reading:
                requested_book = customer.request_book()
                library.lend_book(requested_book)
            else:
                print(f"You are reading {customer.reading_books} book(s) at moment")
            final()
        case 3:
            cls()
            if customer.has_borrowed:
                returned_book = customer.return_book()
                library.add_book(returned_book)
            else:
                print("You have no book to return")
            final()
        case 4:
            cls()
            quit()
        case _:
            cls()
            print("This option is invalid!!!")
            final()
print(book_one.title)
print(book_one.current_page)
print(book_one.author)

book_one.start_reading()

book_one.stop_reading(55)
print(book_one.current_page)

book_one.start_reading()

book_two = Book("Harry Potter and the Chamber of Secrets", "J K Rowling")
print("Book Two:")
print(type(book_two))
print(book_two.title)
print(book_two.current_page)
print(book_two.author)

print("*********************************************")

my_library = Library("My Personal Library")

print(type(my_library))
my_library.add_book(book_one)
print("List of books: ")
my_library.list_books()

# This conditional only evaluates to true if this is file that is excuted ie, `python main.py` from command line.
if __name__ == '__main__':
    print("Hello main file being executed!")
Example #32
0
class LibrarySystemManager:
    def __init__(self, library=None):
        if library is None:
            self.library = Library()
        else:
            self.library = library
        self.logged_person = None

    def run_list_books(self):
        self.library.list_books()

    def run_borrow_book(self):
        book_id = int(input('Type id of the book you want to borrow: '))
        borrowed = self.library.borrow_book(book_id, self.logged_person.login)
        if borrowed:
            print(
                f'{self.logged_person.name}, you borrowed following book: {self.library.get_book_by_id(book_id)}'
            )
        else:
            print(
                f'{self.logged_person.name}, unfortunately this book is already taken.'
            )

    def run_search_a_book(self):
        phrase = input("Type a search phrase: ")
        print("Results:")
        print([
            f'ID: {book.id}, title: {book.title}, author: {book.author}, year: {book.year}'
            for book in self.library.search_for_book(phrase)
        ])

    def run_book_return(self):
        book_id = input('Type book id that is to be returned: ')
        is_returned = self.library.manage_book_return(book_id)
        if is_returned:
            print(f'Book with id: {book_id} returned successfully.')
        else:
            print(f'There is no rent book with id: {book_id}')

    def run_add_new_book(self):
        next_free_id = self.library.books[0].id
        for book in self.library.books:
            if book.id > next_free_id:
                next_free_id = book.id
        next_free_id += 1
        book_id = input(f'Book id (Next free id is: {next_free_id}): ')
        title = input('Book title: ')
        author = input('Book author: ')
        year = int(input('Book year: '))
        book_added = self.library.add_book(title, author, year, book_id)
        if book_added:
            print(f'Book with id {book_id} added successfully.')
        else:
            print(
                f'Could not add book with id {book_id} (Either id or year is wrong).'
            )

    def run_delete_a_book(self):
        book_id = input('Type book id you want to delete: ')
        is_deleted = self.library.delete_book(book_id)
        if is_deleted:
            print(f'Book with id {book_id} deleted successfully')
        else:
            print(f'There is no book with id: {book_id}')

    def run_add_new_reader(self):
        flag = False
        while not flag:
            name = input('Type name of a reader: ')
            surname = input('Type surname of a reader: ')
            login = input('Type login of a reader (must be unique): ')
            password = getpass(prompt='Password: '******'User {name} {surname} added successfully.')
            else:
                print('Login of a reader must be unique.')

    def run_read_library_status(self):
        self.library.read_library_status()

    def run_save_library_status(self):
        self.library.save_library_status()

    def no_such_option_message(self):
        print("There is no such option. Choose option number from the menu.")

    def login(self):
        login = input(
            "First, log in to the library management system. Type your login: "******"You have successfully logged out.")

    def run(self):
        while True:
            try:
                print(
                    "------------------ Library management system ------------------"
                )
                if self.logged_person is None:
                    self.login()
                else:
                    if type(
                            self.logged_person
                    ) == Employee:  # ----------------------Employee--------------------
                        print("1. Manage book return")
                        print("2. Add new book")
                        print("3. Delete book")
                        print("4. Add new reader")
                        print("5. List books")
                        print("6. Log out")
                        print("7. Exit")
                        option = int(input())
                        if option == 1:
                            self.run_book_return()
                        elif option == 2:
                            self.run_add_new_book()
                        elif option == 3:
                            self.run_delete_a_book()
                        elif option == 4:
                            self.run_add_new_reader()
                        elif option == 5:
                            self.run_list_books()
                        elif option == 6:
                            self.logout()
                        elif option == 7:
                            exit()
                        else:
                            self.no_such_option_message()
                        self.run_save_library_status()
                        input("\nType something to get to the menu... ")
                    elif type(
                            self.logged_person
                    ) == Reader:  # --------------------Reader-----------------
                        print("1. List books")
                        print("2. Borrow a book")
                        print("3. Search for a book")
                        print("4. Log out")
                        print("5. Exit")
                        option = int(input())
                        if option == 1:
                            self.run_list_books()
                        elif option == 2:
                            self.run_borrow_book()
                        elif option == 3:
                            self.run_search_a_book()
                        elif option == 4:
                            self.logout()
                        elif option == 5:
                            exit()
                        else:
                            self.no_such_option_message()
                        self.run_save_library_status()
                        input("\nType something to get to the menu... ")
                    else:
                        print(
                            f'No actions available for user type: {type(self.logged_person)}'
                        )
                        input("\nType something to get to the menu... ")
                        self.logged_person = None
            except (ValueError, IndexError, TypeError) as e:
                print(e)