def get_books(): with mysql_connector.db_session() as session: books = session.query(Book).all() books_list = [] for book in books: books_list.append(book.to_dict()) return response.Response(message=books_list)
def delete_book(book_id): with mysql_connector.db_session() as session: existing_book_result = session.query(Book).get(book_id) if not existing_book_result: return response.create_not_found_response() session.delete(existing_book_result) session.commit() return response.Response(message='Successfully deleted book: {}'.format( existing_book_result.BOOK_TITLE))
def update_book(book_id, book_data): with mysql_connector.db_session() as session: existing_book = session.query(Book).get(book_id) if not existing_book: return response.create_not_found_response() for book_prop in book_data: setattr(existing_book, book_prop, book_data.get(book_prop)) session.merge(existing_book) updated_book = existing_book.to_dict() return response.Response(updated_book)
def create_book(book_data): book_model_dict = { 'BOOK_TITLE': book_data.get('title'), 'BOOK_AUTHOR': book_data.get('author'), 'Image_URL_L': book_data.get('imageUrl'), 'shelf': book_data.get('shelf'), 'ISBN': book_data.get('isbn') } book = Book(**book_model_dict) # unpack data with mysql_connector.db_session() as session: session.add(book) session.flush() # send a 201 status for item created vs default of 200 return response.Response(message=book.to_dict(), status=201)
def search_for_books(search_term, search_category): """Search for a book.""" with mysql_connector.db_session() as session: if search_category == 'isbn': results = session.query(LibraryBook).filter( LibraryBook.ISBN.contains(search_term)).limit(20) elif search_category == 'title': results = session.query(LibraryBook).filter( LibraryBook.BOOK_TITLE.contains(search_term)).limit(20) elif search_category == 'author': results = session.query(LibraryBook).filter( LibraryBook.BOOK_AUTHOR.contains(search_term)).limit(20) else: return response.create_error_response(400, 'Invalid Search Category') results_data = [] for book in results: results_data.append(book.to_dict()) return response.Response(results_data)
def get_book_by_id(book_id): """Fetch a book from library by id.""" with mysql_connector.db_session() as session: book = session.query(LibraryBook).get(book_id) book_data = book.to_dict() return response.Response(book_data)