def _loadFile(self):
     try:
         
         f = open(self._fileName, "r")
         s = f.readline()
         
         while len(s)>1:
             tok = s.split(",")
             """
             function to turn string into entity
             """
             if len(tok) == 3:
                 tok[2] = tok[2].split("\n")
                 book = Book(int(tok[0]), tok[1], tok[2][0])
             else:
                 tok[3] = tok[3].split("\n")
                 book = Book(int(tok[0]), tok[1], tok[2], tok[3][0])
             BookRepository.add(self, book)
             s = f.readline()
         
         
     except Exception as e:
         raise RepoError("Error reading input file: " + str(e))
     finally:
         f.close()
Exemplo n.º 2
0
    def json_to_book(self, json_book):

        if "description" in json_book:
            return Book(int(json_book["id"]), json_book["title"],
                        json_book["author"], json_book["description"])
        return Book(int(json_book["id"]), json_book["title"],
                    json_book["author"])
    def test_Repo(self):

        self.assertEqual(len(self.__repo), 0)
        self.__repo.add(self.__book)
        self.assertEqual(len(self.__repo), 1)

        with self.assertRaises(RepoError):
            self.__repo.add(self.__book)

        with self.assertRaises(RepoError):
            self.__repo.remove(self.__nobook)

        with self.assertRaises(RepoError):
            self.__repo.update(self.__nobook)

        self.__repo.update(self.__book)
        self.assertEqual( self.__repo.list(), \
                          "ID \t Title \t  Author \t\t\t\t Description \n {},  {} by {},  described as follows: {}\n".\
                          format(self.__id, self.__title,self.__author,self.__description))
        self.__repo.remove(self.__book)
        with self.assertRaises(RepoError):
            self.__repo.list()

        self.__repo.add(self.__book)
        book = Book(45, "ASC", "Vancea", "du-te la cursurile de ASC")
        self.__repo.add(book)
        self.assertEqual(self.__repo.find(45), book)
        self.assertEqual(self.__repo.find(9), None)

        self.assertEqual(self.__repo.exists_book(book), True)
        self.assertNotEqual(len(self.__repo.get_books()), 0)
        self.assertEqual(len(self.__repo.search_id(45)), 1)
        self.assertEqual(len(self.__repo.search_author("van")), 1)
        self.assertEqual(len(self.__repo.search_description("ursuri")), 1)
        self.assertEqual(len(self.__repo.search_title("asc")), 1)
def book1():
    book = Book(book_id=1,
                title='Old Man',
                publish_date='1980',
                subject='Fiction',
                genre='Novel')
    return book
def book2():
    book = Book(book_id=2,
                title='The Left Hand of Darkness',
                publish_date='1975',
                subject='Fiction',
                genre='Science Fiction')
    return book
Exemplo n.º 6
0
def get_item():
    """
    renders the item.html file
    """
    with Book() as book:
        books, json_data = book.get_all()
    return render_template('item.html', books=books, json_data=json_data)
Exemplo n.º 7
0
def create_data():
    """
    Creates a new document in the mongodb database.
    """
    json_data = request.get_json()
    with Book() as book:
        book.insertDocument(json_data)
    return make_response(jsonify({'req': ''}), 200)
Exemplo n.º 8
0
 def createBook(self, bookList):
     author = bookList[0]
     pages = int(bookList[1])
     isbn = bookList[2]
     title = bookList[3]
     publisher = bookList[4]
     year = int(bookList[5])
     return Book(author, pages, isbn, title, publisher, year)
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.__id = 23
        self.__title = "FP"
        self.__description = "work on your assignments daily"
        self.__author = "Arthur Molnar"
        self.__book = Book(self.__id, self.__title, self.__author,
                           self.__description)

        self.__noid = -85
        self.__notitle = ""
        self.__noauthor = ""
        self.__nobook = Book(self.__noid, self.__notitle, self.__noauthor,
                             self.__description)

        self.__validator = BookValidator()
        self.__repo = BookRepository()
Exemplo n.º 10
0
def insertBook():
    params = get_param()
    store = BookStore.get(params['storeName'])
    book = Book(store.id, params["bookName"], params["price"])
    book.insert()
    return {
        "message": "Insert done!"
    }
Exemplo n.º 11
0
def update_data():
    """
    Updates a document in the mongodb database.
    """
    json_data = request.get_json()
    _id = json_data['_id']['$oid']
    with Book() as book:
        book.updateDocument(_id, json_data)
    return make_response(jsonify({'req': ''}), 200)
Exemplo n.º 12
0
    def reandAdCreateBook(self) -> Book:
        title = input("Podaj tytuł: ")
        author = input("Autor: ")
        publisher = input("Wydawnictwo: ")
        isbn = input("ISBN: ")
        relaseDate = int(input("Rok wydania: "))
        pages = int(input("Podaj liczbe stron: "))

        return Book(author, pages, isbn, title, publisher, relaseDate)
Exemplo n.º 13
0
 def gridbooksCurrentCellChanged(self):
   cell = self.getCurrentCell()
   if cell is False:
     return
   index=cell.RowIndex
   trace.printlog('currentRowIndex:'+str(index))
   dt=self.view.getattr('gridbooks', 'DataSource')
   dr=dt.Rows[index]
   book = Book(dr['Id'], dr['BookName'], dr['BuyPrice'], dr['BuyDate'], dr['Flag'])
   self.setcurrbook(book)
Exemplo n.º 14
0
def parse_document_list(document_list):
    """
    Determines the type of documents in the file and adds them to the library
    """
    for i in range(
            0, len(document_list)
    ):  # Iterates through the list via index, in order to make parsing a bit easier
        if ":" not in document_list[
                i]:  # Makes sure we're processing full documents
            doc_type = document_list[i].strip().rstrip()
            doc_key = document_list[i + 1][4:].strip().rstrip()
            author_list = document_list[i + 2][7:].strip().rstrip().split(",")
            if "Book".lower() in doc_type.lower():
                settings.LIBRARY[doc_key.lower()] = Book(
                    doc_key,  # Book Key
                    author_list,  # Adds author
                    document_list[i + 3][7:].strip().rstrip(),  # Adds title
                    document_list[i +
                                  4][11:].strip().rstrip(),  # Adds publisher
                    document_list[i + 5][6:].strip().rstrip(),  # Adds date
                    doc_type.strip().rstrip()  # Add doc type
                )
            elif "Journal".lower() in doc_type.lower():
                settings.LIBRARY[doc_key.lower()] = Journal(
                    doc_key,  # Journal key
                    author_list,  # Adds author
                    document_list[i + 3][7:].strip().rstrip(),  # Adds title
                    document_list[i + 4][9:].strip().rstrip(),  # Adds Journal
                    document_list[i +
                                  5][11:].strip().rstrip(),  # Adds publisher
                    document_list[i + 6][6:].strip().rstrip(),  # Adds date
                    document_list[i + 7][8:].strip().rstrip(),  # Adds Volume
                    document_list[i + 8][8:].strip().rstrip(),  # Adds Number
                    doc_type  # Adds type
                )
            elif "Conference".lower() in doc_type.lower():
                settings.LIBRARY[doc_key.lower()] = Conference(
                    doc_key,  # Conference key
                    author_list,  # Adds authors
                    document_list[i + 3][7:].strip().rstrip(),  # Adds title
                    document_list[i +
                                  4][12:].strip().rstrip(),  # Adds Conference
                    document_list[i + 5][6:].strip().rstrip(),  # Adds date
                    document_list[i +
                                  6][10:].strip().rstrip(),  # Adds location
                    document_list[i + 7][7:].strip().rstrip(),  # Adds pages
                    doc_type  # Adds type
                )
            else:
                print(
                    f"One of the documents in the list is not a recognized type. Document type: {doc_type}; With key: {doc_key}"
                )
        else:
            continue  # Skips the line b/c its not the start of a document
Exemplo n.º 15
0
def index():
    """
    renders the homepage.
    """
    with Book() as book:
        books, json_data = book.get_all()
    item = get_item()
    return render_template('index.html',
                           books=books,
                           item=item,
                           json_data=json_data)
Exemplo n.º 16
0
async def get_book_with_isbn(isbn: str):
    author_dict = {"name": "name1", "book": ["book1", "book2"]}
    author1 = Author(**author_dict)

    book_dict = {
        "name": "mr kishan",
        "isbn": "124",
        "author": author1,
        "year": 1292
    }
    book1 = Book(**book_dict)
    return book1
Exemplo n.º 17
0
 def __can_rent(self, bid, cid):
     """
     Verifies if the book and the client exist so that the rent makes sense
     Input: bid  - positive integer
            cid - positive integer
     Output: True if the book which identifies with bid and the client which identifies with cid exist
             False otherwise
     """
     book = Book(bid, None, None, None)
     client = Client(cid, None)
     if self.__book_repo.exists_book(book) and self.__client_repo.exists_client(client):
         return True
     return False
    def create(book_dict):
        """
        Method to create a new Book record given a book dictionary. Does NOT create associated Author or BookCopy
        records.
        :param book_dict: dictionary of book values for a new record.
        :return: a dictionary object of the created book.
        """
        print("BookDao.create()")

        new_book = Book(**book_dict)
        new_book.publish_date = parser.parse(new_book.publish_date)
        db.session.add(new_book)
        db.session.commit()
        print("book_dao.create() ==> Complete")
        return new_book.to_dict()
Exemplo n.º 19
0
def to_model(transport):
    return Book(book_id=transport.id,
                title=transport.title,
                synopsis=transport.synopsis,
                isbn10=transport.isbn10,
                isbn13=transport.isbn13,
                language=transport.language,
                publisher=transport.publisher,
                edition=transport.edition,
                paperback_price=transport.paperback_price,
                ebook_price=transport.ebook_price,
                sold_amount=transport.sold_amount,
                current_amount=transport.current_amount,
                category=transport.category,
                created_time=transport.created_time,
                modified_time=transport.modified_time)
Exemplo n.º 20
0
 def testBook(self):
     '''
     Method to test the getter and the setter of the Book class
     '''
     book = Book(1, "Introduction to algorithms", "The Bible",
                 "Thomas H Cormen")
     self.assertEqual(self.getId(), 1)
     assert book.getTitle() == "Introduction to algorithms"
     assert book.getDescription() == "The Bible"
     assert book.getAuthor() == "Thomas H Cormen"
     book.setAuthor("Cosmin")
     assert book.getAuthor() == "Cosmin"
     book.setTitle("Title")
     assert book.getTitle() == "Title"
     book.setDescription("Descr")
     assert book.getDescription() == "Descr"
 def update_book (self, bid, title, author,  description = None):
     """
     Creates a book with the given attributes and updates the book with the same id, 
     already existing in the repository 
     Input: bid -  positive integer (already existing in one of the books from the repository)
            title, author - string
            description - string (default value the empty string)
     
     """
     book = Book(bid, title, author, description)
     self.__book_valid.valid_book(book)
     b = self.__book_repo.update(book)
     
     redo = FunctionCall(self.update_book, bid, title, author, description)
     undo = FunctionCall(self.update_book, bid, b.get_title(), b.get_author(), b.get_description())
     oper = Operations(undo, redo)
     self.__undoService.add(oper)
Exemplo n.º 22
0
def get_content(html):
    """Collect content from the page for the specified classes."""
    soup = BeautifulSoup(html, 'html.parser')
    books = []
    for item in soup.find_all('div', class_='bookkitem'):
        books.append(Book(
            item.find('a', class_='bookkitem_name')
                .get_text(strip=True),

            item.find('div', class_='bookkitem_genre')
                .get_text(strip=True)
                .replace('\n', ''),

            item.find('span', class_='bookkitem_author')
                .get_text(strip=True)
                .replace('авторы', '')
                .replace('автор', '')
            if item.find('span', class_='bookkitem_author')
            else 'Автор неизвестен',

            item.find('div', class_='bookkitem_meta_block')
                .get_text(strip=True)
                .replace('Читает', '')
                .replace('Читают', '')
            if 'минут' not in item.find('div', class_='bookkitem_meta_block')
                                  .get_text(strip=True)
                                  .replace('Читает', '')
                                  .replace('Читают', '')
            else 'Исполнитель неизвестен',

            item.find('div', class_='bookkitem_about')
                .get_text(strip=True)
                .replace('\n', '')
                .replace('\r', '')
                .replace('/', '')
                .replace('а́', 'а')
                .replace('и́', 'и')
                .replace('о́', 'о'),

            HOST + item.find('a', class_='bookkitem_cover')
                       .get('href')
        ))

    return books
 def add_book(self, bid, title, author, description = None):
     """
     Creates a book with the given attributes and adds it in the repository
     Input: bid -  positive integer 
            title, author - string
            description - string (default value the empty string)
     
     """
     book = Book(bid, title, author, description)
     self.__book_valid.valid_book(book)
     self.__book_repo.add(book)
     
     """
     If everything works fine, we try to implement undo and redo command
     """
     redo = FunctionCall(self.add_book, bid, title, author, description)
     undo = FunctionCall(self.remove_book, bid)
     oper = Operations(undo, redo)
     self.__undoService.add(oper)
    def setUp(self):

        self.__id_b = 23
        self.__title = "FP"
        self.__description = "work on your assignments daily"
        self.__author = "Arthur Molnar"
        self.__book = Book(self.__id_b, self.__title, self.__author,
                           self.__description)

        self.__id_cl = 3
        self.__name = "Corina"
        self.__client = Client(self.__id_cl, self.__name)

        self.__rid = 4
        self.__bid = 8
        self.__cid = 2
        self.__rdate = "25.11.2018"
        self.__duedate = "2.12.2018"
        self.__returdate = "28.11.2018"
        self.__rental = Rental(self.__rid, self.__bid, self.__cid,
                               self.__rdate, self.__duedate, self.__returdate)

        self.__bvalid = BookValidator()
        self.__cvalid = ClientValidator()
        self.__rvalid = RentalValidator()

        self.__brepo = BookRepository()
        self.__crepo = ClientRepository()
        self.__rrepo = RentalRepository()

        self.__undoserv = UndoService()

        self.__rental_serv = RentalService(
            self.__rrepo,
            self.__rvalid,
            self.__brepo,
            self.__crepo,
            self.__undoserv,
        )
        self.__book_serv = BookService(self.__brepo, self.__bvalid,
                                       self.__undoserv, self.__rental_serv)
        self.__client_serv = ClientService(self.__crepo, self.__cvalid,
                                           self.__undoserv, self.__rental_serv)
Exemplo n.º 25
0
 def get_book(self, book_id):
     book_from_db = None
     conn = self.db_connection_pool.getconn()
     try:
         with conn.cursor() as cursor:
             sql = """
                     SELECT {columns}
                     FROM book WHERE id=%s
                 """.format(columns=BookRepository.columns)
             cursor.execute(sql, (book_id, ))
             result = cursor.fetchone()
             if result is not None:
                 book_from_db = Book(result[0], result[1], result[2],
                                     result[3], result[4], result[5],
                                     result[6], result[7], result[8],
                                     result[9], result[10], result[11],
                                     result[12], result[13], result[14])
     finally:
         self.db_connection_pool.putconn(conn)
     return book_from_db
Exemplo n.º 26
0
 def deepCopy(self, other):
     '''
     Function to deepCopy another LibraryRepository to this (self) one
     It copies all the data from another Repository to this one with no references of the objects (so that the states do not
         depend at all)
     :param other: another LibraryRepository
     '''
     self._books = [
         Book(book.getId(), book.getTitle(), book.getDescription(),
              book.getAuthor()) for book in other.getBooks()
     ]
     self._clients = [
         Client(client.getCnp(), client.getName())
         for client in other.getClients()
     ]
     self._loans = [
         Loan(self.searchClient(loan.getClient().getCnp()),
              self.searchBook(loan.getBook().getId()))
         for loan in other.getLoans()
     ]
Exemplo n.º 27
0
def create_books(db_type, input_file, bad_data_file):
    session = session_factory(db_type)
    print(session)
    loop_var = 0
    if input_file.mode == 'r':
        for book_data in input_file:
            print(loop_var)
            # ignore header row
            if loop_var == 0:
                loop_var = 1
                continue
            book_data_list = book_data.rstrip().replace('\n', '').replace(
                '"', '').split(";")

            if len(book_data_list) == 8:
                try:
                    ISBN = book_data_list[0]
                    bookTitle = book_data_list[1]
                    bookAuthor = book_data_list[2]
                    yearOfPublication = int(book_data_list[3].replace('"', ''))
                    publisher = book_data_list[4]
                    imageURLS = book_data_list[5]
                    imageURLM = book_data_list[6]
                    imageURLL = book_data_list[7]
                    bookObj = Book(ISBN, bookTitle, bookAuthor,
                                   yearOfPublication, publisher, imageURLS,
                                   imageURLM, imageURLL)
                    session.add(bookObj)
                    session.commit()
                except:
                    # put data into bad_data_file
                    bad_data_file.write(book_data)
            else:
                bad_data_file.write(book_data)
            loop_var = loop_var + 1  # used for checking the execution
        loop_var = 0
    session.commit()
    session.close()
 def remove_book(self, bid ):
     """
     Removes the book with the given id from the repository
     Input: bid - positive integer
     """
     book = Book(bid, None, None, None)
     b = self.__book_repo.remove(book)
     
     """
     delete the rentals\
     """
     rentals = self.__rental_service.filter_rentals(bid, None)
     
     for r in rentals:
         self.__rental_service.remove_rental(r.get_id())
     
     
     undo = FunctionCall(self.add_book,b.get_id(), b.get_title(), b.get_author(), b.get_description())
     redo = FunctionCall(self.remove_book, bid)
     oper1 = Operations(undo, redo)
     
     co = CascadeOperations()
     co.add(oper1)
     
     if len(rentals)!= 0 :
         for r in rentals:
             rdate = date_to_str_format(r.get_rent_date())
             ddate = date_to_str_format( r.get_due_date())
             if r.get_returned_date() != None:
                 retdate = date_to_str_format(r.get_returned_date())
                 undo = FunctionCall(self.__rental_service.rent,r.get_id(),r.get_b_id(), r.get_c_id(), rdate, ddate, retdate)
             else:
                 undo = FunctionCall(self.__rental_service.rent,r.get_id(),r.get_b_id(), r.get_c_id(), rdate, ddate)
             redo = FunctionCall(self.__rental_service.remove_rental, r.get_id())
             oper = Operations(undo, redo)
             co.add(oper)
     
     self.__undoService.add(co)
Exemplo n.º 29
0
Arquivo: dao.py Projeto: Ziem0/Library
 def load_library():
     if not os.path.isfile('static/books.csv'):
         raise FileNotFoundError
     else:
         with open('static/books.csv', 'r') as f:
             for item in f:
                 item = item.strip('\n')
                 item = item.split(',')
                 if item[0] == 'book':
                     author = item[1]
                     title = item[2]
                     book = Book(author, title)
                     book.add_copy(int(item[3]))
                     for copy in book.copies:
                         if item[5] == 'y':
                             copy.is_short_term = True
                     for copy in book.copies[:int(item[4])]:
                         copy.is_borrowed = True
                 else:
                     title = item[1]
                     number = item[2]
                     journal = Journal(title, number)
                     if item[3] == 'y':
                         journal.is_borrowed = True
Exemplo n.º 30
0
 def query_book(self, query):
     books = []
     conn = self.db_connection_pool.getconn()
     try:
         with conn.cursor() as cursor:
             filter_sql = ""
             if query['title'] is not None:
                 filter_sql = " WHERE title like '%{}%' ".format(
                     query['title'])
             if query['order_by'] is None:
                 query['order_by'] = 'createdtime'
             sql = "SELECT {columns} FROM book {filter} ORDER BY {order_field} DESC LIMIT {limit} OFFSET {offset} "\
                 .format(columns=BookRepository.columns, limit=query['limit'],
                         offset=query['offset'], filter=filter_sql, order_field=query['order_by'])
             cursor.execute(sql)
             result = cursor.fetchall()
             for each in result:
                 books.append(
                     Book(each[0], each[1], each[2], each[3], each[4],
                          each[5], each[6], each[7], each[8], each[9],
                          each[10], each[11], each[12], each[13], each[14]))
     finally:
         self.db_connection_pool.putconn(conn)
     return books