def newBook(): if request.method == 'POST': newBook = Books(name=request.form['name'], description=request.form['description'], img_url=request.form['img_url']) DBSession = sessionmaker(bind=engine) session = DBSession() session.add(newBook) session.commit() # flash("new book inserted!") print("New Book Inserted") return jsonify(Book=newBook.serialize)
def newBook(): DBSession = sessionmaker(bind=engine) session = DBSession() if request.method == 'POST': newBook = Books(name=request.form['name'], description=request.form['description'], img_url=request.form['img_url']) session.add(newBook) session.commit() flash("new book inserted!") return redirect(url_for('homePage')) else: return render_template('newbook.html')
def newBook(genre_id): if request.method == 'POST': user_id = check_user().id newItem = Books( name=request.form['name'], author=request.form['author'], description=request.form['description'], price=request.form['price'], rating=request.form['rating'], genre_id=genre_id, user_id=user_id) session.add(newItem) session.commit() flash("New book added!") return(redirect(url_for('showBooks', genre_id=genre_id))) else: return render_template('newbook.html', genre_id=genre_id)
def add_book(title, summary, current_genre_id, author_input, user_id, photo): new_book = Books(title=title, summary=summary, genre_id=current_genre_id, user_id=user_id, photo=photo) session.add(new_book) # check if author exists in the DB try: author = session.query(Author).filter_by(name=author_input).one() new_book.author_id = author.id # add author to DB if not except: new_author = Author(name=author_input) session.add(new_author) session.commit() new_book.author_id = new_author.id session.commit() return new_book
def newBook(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': newBook = Books(name=request.form['name'], author=request.form['author'], category=request.form['category'], price=request.form['price'], description=request.form['description'], cover=request.form['cover'], user_id=login_session['user_id']) session.add(newBook) flash('New Book %s Successfully Created' % newBook.name) session.commit() return redirect(url_for('index')) else: return render_template('newBook.html')
def addItem(): categories = session.query(BookCategory).all() if request.method == 'POST': categoryName = request.form['categoryName'] categoryId = (session.query(BookCategory).filter_by( name=categoryName).one().id) newBook = Books(name=request.form['name'], description=request.form['description'], author=request.form['author'], price=request.form['price'], category_id=categoryId, user_id=login_session['user_id']) session.add(newBook) session.commit() return redirect(url_for('getBookCatalog', login_session=login_session)) else: return render_template('add_book.html', categories=categories, login_session=login_session)
def newBook(category_id, title, isbn, url, author, description, user_id): ''' Creates a new books Args: category_id = id of the category the book belongs to title = title of the book isbn = books isbn url = url of the image of the book author = the books author description = the books description user_id = the current user ''' book = Books(title=title, image=url, description=description, author=author, isbn=isbn, category=category_id, user_id=user_id) sess.add(book) sess.commit()
def addBook(): '''Adds a book to the database if the user is logged in''' if loginCheck(): return redirect('/login') DBSession = sessionmaker(bind=engine) session = DBSession() if request.method == 'POST': author_id = authorCheck(request.form['author']) genre_id = genreCheck(request.form['genre']) newBook = Books(title=request.form['title'], genre_id=genre_id, summary=request.form['summary'], author_id=author_id, owner_id=login_session['username']) session.add(newBook) session.commit() flash("New Book Added") return redirect(url_for('showBookList')) else: return render_template('add_book.html')
def addNewBook(genreId): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': artURL = request.form['coverArt'] r = requests.get(artURL, allow_redirects=True) fileName = "/var/www/html/static/" fileName += request.form['title'] fileName += ".jpg" fileName = fileName.replace(' ', '') fileName = fileName.replace("'", "") open(fileName, 'wb').write(r.content) os.chmod(fileName, 0777) fileName = fileName.replace('/var/www/html/static/', '') nBookId = session.query(func.max(Books.id)).scalar() nBookId += 1 newBook = Books(id=nBookId, title=request.form['title'], genre_id=request.form['genre'], author_id=request.form['author'], synopsis=request.form['syn'], cover_art=fileName, user_id=login_session['user_id']) session.add(newBook) session.commit() return redirect(url_for('bookListStart')) else: genres = session.query(Genre).all() authors = session.query(Authors).all() return render_template('newBook.html', genres=genres, authors=authors, genre_id=genreId)
def new_book(): # Check if user is logged in if 'username' not in login_session: return render_template('public.html', genres=genres) genres = session.execute(q_genres) genres = sorted([i[0] for i in genres]) if request.method == 'POST': user_id = getUserID(login_session['email']) existing_authors = \ session.execute(q_get_existing_authors.format(user_id)) existing_authors = [i[0] for i in list(existing_authors)] first_name = request.form['author_first_name'].strip() last_name = request.form['author_last_name'].strip() full_name = first_name + ' ' + last_name print('FULLNAME', full_name) # If author is not in 'authors', add new entry to 'authors' table if full_name not in existing_authors: new_author = Authors(last_name=request.form['author_last_name'], first_name=request.form['author_first_name'], user_id=user_id) session.add(new_author) session.commit() author_id = session.execute("SELECT id \ FROM authors \ WHERE first_name='{}' \ AND last_name='{}';".format(first_name, last_name)) author_id = list(author_id) print('AUTHOR_ID', author_id) author_id = author_id[0][0] genre_id = session.execute("SELECT id \ FROM genres \ WHERE genre='{}';".format(request.form['genre'])) genre_id = list(genre_id)[0][0] genre = request.form['genre'] title = request.form['title'] pages = request.form['pages'] synopsis = request.form['synopsis'] date_finished = request.form['date_finished'] new_item = Books(title=title, author_id=author_id, genre_id=genre_id, pages=pages, synopsis=synopsis, date_finished=date_finished, user_id=user_id) try: session.add(new_item) session.commit() new_book_id = session.execute("SELECT MAX(id) FROM books;") new_book_id = list(new_book_id)[0][0] user_id = getUserID(login_session['email']) info = session.execute(q_book_info.format(new_book_id, user_id)) info = [i for i in list(info)[0]] flash('New book added: {}'.format(info[0])) return render_template('book.html', info=info, book_id=new_book_id, genre=genre) except exc.IntegrityError as e: session.rollback() flash('Error! You already have this book-author pairing: \ {title} by {} {}.'.format(first_name, last_name)) return redirect(url_for('new_book')) else: return render_template('newBook.html', genres=genres)
ruser = random.randrange(1, 4) book1 = Books( title="Take Heart, My Child: A Mother's Dream", image="https://images-na.ssl-images-amazon.com/images/I/515MrbUcuwL.jpg", description=u'''In the tradition of Emily Winfield Martin’s The Wonderful Things You Will Be and Nancy Tillman’s On The Night You Were Born, popular FOX news anchor Ainsley Earhardt’s lyrical lullaby inspires children to follow their dreams and passions. FOX and Friends cohost Ainsley Earhardt’s debut picture book shares precious life lessons parents can pass onto their children so that they can follow their hearts, dreams, and passions. Take Heart, My Child is a lyrical lullaby, and Ainsley shares her own hopes and dreams, and lets her child know that whatever challenges life brings, “Take heart, my child, I will—or, my love will—always be there for you.” It’s a universal message, one that all readers will relate to. In the “Story Behind the Story,” Ainsley talks about growing up and how her father would write messages to her and her siblings each morning, leaving notes at the breakfast table, so that his children would know they were loved, empowered, protected, and cherished.', ''', author="Ainsley Earhardt", isbn="481466224", category=6, user_id=ruser, ) sess.add(book1) sess.commit()
# revert all of them back to the last commit by calling # session.rollback() session = DBSession() # load data from JSON file with open('database_records.json', 'rb') as file: data = json.load(file) # Loop through 'books' data, create 'Book' object for each iteration # and store in database for item in data['books']: book = Books(id=item['id'], title=item['title'], author=item['author'], publisher=item['publisher'], genre=item['genre'], description=item['description'], image_url=item['image_url'], buy_link=item['buy_link'], publish_date=datetime.strptime(item['publish_date'], '%Y-%m-%d')) session.add(book) for item in data['users']: user = Users(email_id=item['email_id'], id=item['id'], name=item['name'], image=item['image']) session.add(user) for item in data['userreadinglist']: readingListEntry = UserReadingList(user_id=item['user_id'],
# session.rollback() session = DBSession() # Create dummy user user1 = User(name="Fahad Abdullah", email="*****@*****.**", picture='https://img.icons8.com/color/96/000000/administrator-male.png') session.add(user1) session.commit() # Items for Strings category1 = Category(name="Action & Adventure ", user_id=1) session.add(category1) session.commit() item1 = Books(name="Harry Potter", user_id=1, description="Harry Potter has never even heard of Hogwarts when the letters start dropping on the doormat at number four, Privet Drive."+ \ " Addressed in green ink on yellowish parchment with a purple seal, they ", category=category1) session.add(item1) session.commit() item2 = Books(name="The Secret Of The Nagas ", user_id=1, description="The Shiva Trilogy, written by Amish Tripathi, has become a nation-wide bestseller in a short time. This is due to the" + \ "refreshing new plot that it explores and the unique writing style of the author. The Secret of The Nagas is the second novel in the saga. Amish has penned down the contents of this book"+ \ "in such a way that it manages to shine as a stand-alone book in itself.", category=category1) session.add(item2) session.commit() item3 = Books(name="Sita: Warrior of Mithila", user_id=1, description="Immerse yourself in book 2 of the Ram Chandra series, based on the Ramayana, the story of Lady Sita, written by the multi-million" + \ "bestselling Indian Author Amish; the author who has transformed Indian Fiction with his unique combination of mystery, mythology, religious symbolism and philosophy. In this book, you will follow Lady Sita's" + \ "journey from an Adopted Child to the Prime Minister to finding her true calling. You will find all the familiar characters you have heard of, like Lord Ram and Lord Lakshman and see more of Lord Hanuman and many" + \ "others from Mithila. You will also start discovering the true purpose of the Vayuputras and Malayaputras and their conflicting ideologies that leads to plot twists, politics and intrigue as they try to influence" + \
category3 = BookCategory(name="Cookbooks") session.add(category3) session.commit() category4 = BookCategory(name="History") session.add(category4) session.commit() category5 = BookCategory(name="Literature") session.add(category5) session.commit() # Books for category fiction Book1 = Books(name="1984", author="George Orwell", description="Among the seminal texts of the 20th century, Nineteen Eighty Four is a rare work that grows more haunting as its futuristic purgatory becomes more real. Published in 1949, the book offers political satirist.", price='$4.00', category_id=1, user_id=1) session.add(Book1) session.commit() Book2 = Books(name="A tale of two cities", author="Charles Dickens", description="After eighteen years as a political prisoner in the Bastille, the ageing Doctor Manette is finally released and reunited with his daughter in England. There the lives of two very different men, Charles Darnay, an exiled French aristocrat, and Sydney Carton, a disreputable but brilliant English lawyer, become enmeshed through their love for Lucie Manette. From the tranquil roads of London, they are drawn against their will to the vengeful, bloodstained streets of Paris at the height of the Reign of Terror, and they soon fall under the lethal shadow of La Guillotine.", price='$4.00', category_id=1, user_id=1) session.add(Book2) session.commit() Book3 = Books(name="The Paying Guests", author="Sarah Waters", description=" A psychological and dramatic tour de force from beloved international bestseller Sarah Waters. The year is 1922, and London is tense. Ex-servicemen are disillusioned, the out of work and the hungry are demanding change", price='$4.00', category_id=1, user_id=1) session.add(Book3) session.commit() # Books for category Non Fiction Book4 = Books(name="Atomic Habits", author="James Clear", description="No matter your goals, Atomic Habits offers a proven framework for improving--every day. James Clear, one of the world's leading experts on habit formation, reveals practical strategies that will teach you exactly how to form good habits, break bad ones, and master the tiny behaviors that lead to remarkable results.", price='$4.00', category_id=2, user_id=1) session.add(Book4)
session.commit() genre4 = Genres(name='Magic Realism') session.add(genre4) session.commit() genre5 = Genres(name='African-American Literature') session.add(genre5) session.commit() print "Genres added" book1 = Books( title="Harry Potter and the Philosopher's Stone", genre=genre1, summary= "The first novel in the Harry Potter series and Rowling's debut novel, it follows Harry Potter, a young wizard who discovers his magical heritage on his eleventh birthday, when he receives a letter of acceptance to Hogwarts School of Witchcraft and Wizardry. Harry makes close friends and a few enemies during his first year at the school, and with the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just 15 months old.", authors=author1, patrons=patron1, owner_id='null') session.add(book1) session.commit() book2 = Books( title="Harry Potter and the Chamber of Secrets", genre=genre1, summary= "The second novel in the Harry Potter series. The plot follows Harry's second year at Hogwarts School of Witchcraft and Wizardry, during which a series of messages on the walls of the school's corridors warn that the Chamber of Secrets has been opened and that the heir of Slytherin would kill all pupils who do not come from all-magical families. These threats are found after attacks which leave residents of the school petrified. Throughout the year, Harry and his friends Ron and Hermione investigate the attacks.", authors=author1, owner_id='null') session.add(book2) session.commit()
# First Genres genre1 = Genre(id=1, genre="SciFi", user_id=1) genre2 = Genre(id=2, genre="Fantasy", user_id=1) session.add(genre1) session.commit() session.add(genre2) session.commit() # First Books book1 = Books(id=1, title="The Rowan", cover_art="TheRowan.jpg", synopsis="Book 1 of the Rowan Series", genre_id=1, author_id=1, user_id=1) book2 = Books(id=2, title="Damia", cover_art="Damia.jpg", synopsis="Book 2 of the Rowan series", genre_id=1, author_id=1, user_id=1) book3 = Books(id=3, title="Damia's Children", cover_art="DamiasChildren.jpg",
def new_book(): # Check if user is logged in if 'username' not in login_session: return render_template('public.html', genres=genres) genres = session.execute(q_genres) genres = sorted([i[0] for i in genres]) if request.method == 'POST': # EXAMPLE row: # 1 War and Peace 1 HIF 1225 The novel chronicles the history of the French invasion of Russia and the impact of the Napoleonic era on Tsarist society through the stories of five Russian aristocratic families. 2019-01-01 user_id = getUserID(login_session['email']) existing_authors = session.execute( q_get_existing_authors.format(user_id)) existing_authors = [i[0] for i in list(existing_authors)] first_name = request.form['author_first_name'].strip() last_name = request.form['author_last_name'].strip() full_name = first_name + ' ' + last_name # If author is not in 'authors', add new entry to 'authors' table if full_name not in existing_authors: new_author = Authors(last_name=request.form['author_last_name'], first_name=request.form['author_first_name']) session.add(new_author) session.commit() author_id = session.execute( f"SELECT id FROM authors WHERE first_name='{first_name}' AND last_name='{last_name}';" ) author_id = list(author_id)[0][0] genre_id = session.execute( f"SELECT id FROM genres WHERE genre='{request.form['genre']}';") genre_id = list(genre_id)[0][0] title = request.form['title'] pages = request.form['pages'] synopsis = request.form['synopsis'] date_finished = request.form['date_finished'] new_item = Books(title=title, author_id=author_id, genre_id=genre_id, pages=pages, synopsis=synopsis, date_finished=date_finished, user_id=user_id) try: session.add(new_item) session.commit() new_book_id = session.execute(f"SELECT MAX(id) FROM books;") new_book_id = list(new_book_id)[0][0] user_id = getUserID(login_session['email']) print('USERID', user_id) info = session.execute(q_book_info.format(new_book_id, user_id)) print(info) info = [i for i in list(info)[0]] print(info) flash(f'New book added: {info[0]}') return render_template('book.html', info=info, book_id=new_book_id) except exc.IntegrityError as e: session.rollback() flash( f'Error! You already have this book-author pairing: {title} by {first_name} {last_name}.' ) return redirect(url_for('new_book')) else: return render_template('newBook.html', genres=genres)
# rollback is used to revert any change session = DBSession() # *Create Dummy Data # 1. Create dummy user user_1 = User(username="******", email="*****@*****.**") session.add(user_1) session.commit() # 2. create dummy books data book_1 = Books( name="The School of Greatness: A Real-World Guide to Living Bigger, Loving Deeper, and Leaving a Legacy", price="16.58", author="LEWIS HOWES", cover="https://images-na.ssl-images-amazon.com/images/I/517-Dn1lhtL._SX323_BO1,204,203,200_.jpg", description='A framework for personal development...', category="Motivation", user_id=1 ) session.add(book_1) session.commit() book_2 = Books( name="Unshakeable Your Financial Freedom Playbook", price="18.20", author="Tony Robbins", cover="https://images-na.ssl-images-amazon.com/images/I/516Ic5gWnfL._SX328_BO1,204,203,200_.jpg", description="After interviewing fifty of the worlds greatest financial minds ...", category="Finance", user_id=1