Ejemplo n.º 1
0
    def test_save_update_changes_to_db(self):

        bk = Book(author='CCC', title='DDD', read=True)
        bk.save()

        # Change some attributes and save
        bk.author = 'EEE'
        bk.title = 'FFF'
        bk.read = False

        bk.save()

        # Check DB has same data as bk Book object
        self.assertEqual(bk, bookstore.get_book_by_id(bk.id))
        self.assertTrue(bk, bookstore.exact_match(bk))
Ejemplo n.º 2
0
def add_new_book(title, genre, author_name):
    """Adds a new book to the system"""
    # Get the author's first and last names
    first_name, _, last_name = author_name.partition(" ")

    # Check if book exists
    book = (session.query(Book).join(Author).filter(
        Book.title == title).filter(
            and_(Author.first_name == first_name,
                 Author.last_name == last_name)).one_or_none())

    if book is not None:
        return "Book already exist"

    # Create the new book if needed
    if book is None:
        book = Book(title=title, genre=genre)

    # Get the author
    author = (session.query(Author).filter(
        and_(Author.first_name == first_name,
             Author.last_name == last_name)).one_or_none())

    if author is None:
        return "Author name not exist in the table"

    book.author = author
    session.add(book)
    session.commit()

    d = collections.OrderedDict()
    b = session.query(Book).filter_by(title=title).one()
    d["id"] = b.id
    d["title"] = b.title
    d["genre"] = b.genre
    d["author_id"] = author.author_id
    d["author_firstname"] = author.first_name
    d["author_lastname"] = author.last_name
    j = json.dumps(d)
    return j