def addBook(): # Return "This page will provide a form to add new books" if 'username' not in login_session: return redirect(url_for('showLogin', private=False)) if request.method == 'POST': genre = session.query(Genre).filter_by(id=request.form['genre']).one() user = session.query(User).filter_by(id=login_session['user_id']).one() description = '{}'.format(request.form['description']) book = Book(name=request.form['name'], author=request.form['author'], description=description, cover=request.form['cover'], genre=genre, user=user) session.add(book) session.commit() return redirect( url_for('showGenreItems', genre_id=genre.id, private=True, picture=login_session['picture'])) else: return render_template('createBook.html', private=True, picture=login_session['picture'])
def addBook(genre_id): """ This method adds a new book to the catalog. It takes given image and resize it to thumbanil size and saves it in the given folder. """ if 'username' not in login_session: return redirect(url_for('showLogin')) else: if request.method == 'POST': if request.form['name'] and request.form['price']: newbook = Book(name = request.form['name'], description = request.form['description'], price = request.form['price'], genre_id = genre_id, user_id=login_session.get('user_id') ) file = request.files['picture'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) with Image.open(file) as image: image = resizeimage.resize_contain(image, [100, 150]) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newbook.picture = filename session.add(newbook) session.commit() flash("New book added successfully!!") return redirect(url_for('displayBooks', genre_id = genre_id)) else: return render_template('addBook.html', genre_id = genre_id, login_session = login_session)
def addBook(): if 'name' in login_session and login_session['name'] != 'null': # Check if user is logged in if request.method == 'POST': addBook = Book(name=request.form['name'], author=request.form['author'], cover=request.form['cover'], description=request.form['description'], categories=request.form['categories'], user_id=validateUser().id) session.add(addBook) session.commit() return redirect(url_for('showBookshelf')) else: return render_template('addbook.html', title='Add New Book', message='All Fields Required', login_session=login_session) else: state = showLogin() books = allBooks() return render_template('bookshelf.html', books=books, login_session=login_session, message='Login to Add Book')
def load_books(filename, genres, session, importer): books_data = parse_json_objects_data(filename, 'books') for book_data in books_data: genre_name = book_data.get('genre') if genre_name is None: logging.warning("Missed genre for book {}".format(book_data)) continue genre_query = session.query(Genre).filter_by(name=genre_name) if genre_query.count() == 0: logging.warning("No genre {} (book data: {})".format( genre_name, book_data)) continue if book_data['user'] != importer.name: continue genre = genre_query.one() book_data['genre'] = genre book_data['genre_id'] = genre.id book_data['user'] = importer book_data['user_id'] = importer.id try: book = Book(**book_data) yield book except TypeError: logging.warning("Malformed book data: {}".format(book_data)) continue
def newBook(genre_id): if 'username' not in login_session: return redirect('/login') genre = session.query(Genre).filter_by(id=genre_id).one() if login_session['user_id'] != genre.user_id: return """<script>function myFunction(){ alert('You are not authorized to add books to this genre as you have not created it.'); } </script><body onload='myFunction()''>""" if request.method == 'POST': newBook = Book(picture=request.form['picture'], 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=genre.user_id) session.add(newBook) session.commit() flash("New Book '{}' Successfully Created".format(newBook.name)) return redirect(url_for('showBooks', genre_id=genre_id)) else: return render_template('newbook.html', genre_id=genre_id)
def newBook(category_id): """Creates a new book""" category = session.query(Category).filter_by(id=category_id).one() if request.method == 'POST': if 'submit' in request.form: if request.files['file']: file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(path) # we need to save a slightly different version of the path # in the database. dbpath = path.replace(".", "", 1) else: dbpath = "" newBook = Book(title=request.form['title'], author=request.form['author'], price=request.form['price'], description=request.form['description'], fiction=request.form['fiction'], isbn=request.form['isbn'], published=request.form['published'], category_id=category_id, image=dbpath, user_id=login_session['user_id']) session.add(newBook) session.commit() flash('New Book %s Successfully Created' % (newBook.title)) return redirect(url_for('showBooks', category_id=category_id)) flash('Book Creation Cancelled') return redirect(url_for('showBooks', category_id=category_id)) else: return render_template('newBook.html')
def showBooks(): if request.method == 'POST': ten = request.form['author'] print(ten) if ',' in ten: ten = ten.replace(',', '') print(ten) print(ten.isnumeric()) if ten.isnumeric() and (request.form['genre'].isnumeric() or request.form['genre'] == 'N' or request.form['genre'] == 'B' or request.form['genre'] == ''): try: editedBook = session.query(Book).filter_by( title=request.form['name']).first() editedBook.author = request.form['author'] editedBook.genre = request.form['genre'] session.add(editedBook) session.commit() except: newBook = Book(title=request.form['name'], author=request.form['author'], genre=request.form['genre']) session.add(newBook) session.commit() books = session.query(Book).all() return render_template("books.html", books=books) else: books = session.query(Book).all() return render_template("books.html", books=books)
def add_book(author_id): """ Takes author_id, creates a new book using data from Add Book form in the database, and renders list of all books of the author with author_id. """ if 'username' not in login_session: return redirect('/login') if request.method == 'POST': if request.form['submit-button'] == 'Cancel': return redirect(url_for('show_list', author_id=author_id)) if not request.form['title-to-add']: return render_template('add-book.html', author_id=author_id, empty_title=True) new_book = Book(title=request.form['title-to-add'], description=request.form['description-to-add'], author_id=author_id, user_id=login_session['user_id']) session.add(new_book) session.commit() return redirect(url_for('show_list', author_id=author_id)) else: return render_template('add-book.html', author_id=author_id)
def addBook(): # Check if user is logged in if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # Retain data when there is an error if not request.form['name']: flash('Please add book name') return redirect(url_for('addBook')) if not request.form['description']: flash('Please add a description') return redirect(url_for('addBook')) # Add Book newBook = Book(name=request.form['name'], description=request.form['description'], category_id=request.form['category'], user_id=login_session['user_id']) session.add(newBook) session.commit() return redirect(url_for('showCategories')) else: # Get all categories categories = session.query(Category).all() return render_template('addBook.html', categories=categories)
def showBooks(): if request.method == 'POST': # print(request.form) # if request.form.get('action') == 'Cancel': # print(request.form.get('action')) return render_template('start.html') # else: # print(request.form.get('action')) # bookToDelete = session.query(Book).filter_by(id=book_id).first() engine.execute("DELETE FROM book;") ##engine.execute("SELECT * FROM book WHERE book.title='cola'") ##sengine.execute("UPDATE book SET book.author WHERE book.title='cola'") # print("cola deleted") session.commit() ''' class infofe(object): all_item = [] all_position = [] all_status = [] def __init__(self, item, position, status): self.item = item self.position = position self.status = status infofe.all_item.append(item) infofe.all_position.append(position) infofe.all_status.append(status) ''' url = 'http://192.168.2.17:8000' url = url + '/booksApi' # print(url) resp = requests.get(url) # print(resp.status_code) if resp.status_code == 200: jsonobj = resp.json() y_string = json.dumps(jsonobj) y_store = json.loads(y_string) #print(jsonobj) for element in y_store["books"]: listname = element['title'] listposition = element['author'] liststatus = element['genre'] # print(element['title']) try: editedBook = session.query(Book).filter_by( title=listname).first() editedBook.author = listposition editedBook.genre = liststatus session.add(editedBook) session.commit() # print("Update cola") except: newBook = Book(title=listname, author=listposition, genre=liststatus) session.add(newBook) session.commit() books = session.query(Book).all() return render_template("books.html", books=books)
def newBook(library_id): """ Method: Create a new book in the library. Args: library_id (data type: int): Id of the library. Return: New book form. """ library = session.query(Library).filter_by(id=library_id).one() if login_session['user_id'] != library.user_id: flash('You are not authorized to Edit this Library') return redirect(url_for('showLibraries')) if request.method == 'POST': newBook = Book(name=request.form['name'], description=request.form['description'], price=request.form['price'], genre=request.form['genre'], library_id=library_id) session.add(newBook) session.commit() flash('New Book %s added to the library successfully' % (newBook.name)) return redirect(url_for('showBook', library_id=library_id)) else: return render_template('newbook.html', library_id=library_id, user=login_session['username'])
def createBook(genre_id): ''' Return template to create new book in catalog. If user not logged in redirects to login page. ''' genre = session.query(Genre).filter_by(id=genre_id).one() if 'username' not in login_session: return redirect(url_for('login')) else: if request.method == 'POST': newBook = Book(title=request.form['title'], author=request.form['author'], synopsis=request.form['synopsis'], cover_image=request.form['cover_image'], genre_id=genre_id, user_id=login_session['user_id']) session.add(newBook) session.commit() flash("You added " + newBook.title + " to your library!") return redirect( url_for('getBook', genre_id=genre.id, book_id=newBook.id, login_session=login_session)) else: return render_template('createbook.html', genre=genre, login_session=login_session)
def add_book(): """Create a new item. Note: This route will list all the categories that the logged-in user has created. There is another module called `add_item_by_category()` which creates items based on the endpoint of the category mentioned. """ if 'username' not in login_session: flash("Please log in to continue.") return redirect(url_for('login')) elif request.method == 'POST': # Check if the item already exists in the database. # If it does, display an error. book = session.query(Book).filter_by(name=request.form['name']).first() if book: if book.name == request.form['name']: flash('The book already exists in the database!') return redirect(url_for("add_book")) new_book = Book(name=request.form['name'], genre_id=request.form['genre'], description=request.form['description'], user_id=login_session['user_id']) session.add(new_book) session.commit() flash('New book successfully created!') return redirect(url_for('home')) else: books = session.query(Book).\ filter_by(user_id=login_session['user_id']).all() genre = session.query(Genre).all() return render_template('new-book.html', books=books, genre=genre)
def add_book_by_genre(genre_id): """Create new item by Category ID.""" if 'username' not in login_session: flash("You were not authorised to access that page.") return redirect(url_for('login')) elif request.method == 'POST': # Check if the item already exists in the database. # If it does, display an error. book = session.query(Book).filter_by(name=request.form['name']).first() if book: if book.name == request.form['name']: flash('The item already exists in the database!') return redirect(url_for("add_book")) new_book = Book(name=request.form['name'], genre_id=genre_id, description=request.form['description'], user_id=login_session['user_id']) session.add(new_book) session.commit() flash('New book successfully created!') return redirect(url_for('show_books_in_genre', genre_id=genre_id)) else: genre = session.query(Genre).filter_by(id=genre_id).first() return render_template('new-book-2.html', genre=genre)
def newBook(category_id): if 'username' not in login_session: flash('Please login to continue.') return redirect('/login') if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newItem = Book(name=request.form['name'], picture=filename, author=request.form['author'], description=request.form['description'], category_id=category_id, user_id=login_session['user_id']) session.add(newItem) session.commit() flash("New book successfully created for %s." % newItem.name) return redirect(url_for('books', category_id=category_id)) else: return render_template('create.html', category_id=category_id)
def createBook(): newBook = Book(title=request.form['name'], author=request.form['author'], genre=request.form['genre']) session.add(newBook) session.commit() return newBook
def addBook(library_id): """Add a new book Args: library_id: The id of the library which will own the book Returns: on GET: Page to add a new book on POST: Redirct to book page after adding a new book """ if 'username' not in login_session: return redirect('/login') library = session.query(Library).filter_by(id=library_id).one() if login_session['user_id'] != library.user_id: return "<script>function myFunction() {alert('You are not authorized \ to add books to this library. Please create your own library \ in order to add books.');}</script><body onload='myFunction()'>" if request.method == 'POST': newBook = Book(name=request.form['name'], description=request.form['description'], author=request.form['author'], category=request.form['category'], library_id=library_id, user_id=library.user_id) session.add(newBook) session.commit() flash('New Book %s Item Successfully Added' % (newBook.name)) return redirect(url_for('showBook', library_id=library_id)) else: return render_template('addBook.html', library_id=library_id)
def post(self): new_title = request.form['title'] new_author = request.form['author'] new_genre = request.form['genre'] new_record = Book(title=new_title, author=new_author, genre=new_genre) db.session.add(new_record) db.session.commit() return make_response(render_template('book.html', result=new_record))
def add_entries(data): """ Create book objects for each title - author """ for row in data.values(): if is_alphanum(row['name']): book = Book(name=row['name'], author=row['author']) yield book
def makeANewBook(vaccine, lab, quantity, orderby): addedbook = Book(vaccine=vaccine, lab=lab, quantity=quantity, orderby=orderby) session.add(addedbook) session.commit() return jsonify(vaccines=addedbook.serialize)
def newBook(): if request.method == 'POST': newBook = Book(title = request.form['name'], author = request.form['author'], genre = request.form['genre']) db.session.add(newBook) db.session.commit() return redirect(url_for('showBooks')) else: return render_template('newBook.html')
def add_book_post_handler(genre): form_is_valid, book_args = validate_fields() if not form_is_valid: return abort(400) book_args['user_id'] = login_session['user_id'] book = Book(**book_args) session.add(book) session.commit() flash("Book successfully added") return redirect(url_for('show_book', book_title=book.build_url()))
def addBook(): # Creates the record and saves it to the database if request.form: new_item = Book(name=request.form['name'], author=request.form['author']) session.add(new_item) session.commit() requests.get(f'http://localhost:2020/book/genre/{new_item.id}') return redirect(url_for('homePage'))
def newBook(): if request.method == "POST": newBook = Book( title=request.form["name"], author=request.form["author"], genre=request.form["genre"], ) session.add(newBook) session.commit() return redirect(url_for("showBooks")) else: return render_template("newBook.html")
def newBook(): if request.method == 'POST': title = request.form['name'] author = request.form['author'] genre = request.form['genre'] newBook = Book(title=title, author=author, genre=genre) session.add(newBook) session.commit() print(title, author, genre) return redirect(url_for('showBooks')) else: return render_template('newBook.html')
def do_POST(self): try: if self.path.endswith("/edit"): ctype, pdict = cgi.parse_header( self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile, pdict) messagecontent = fields.get('newBookName') bookIDPath = self.path.split("/")[2] myBookQuery = session.query(Book).filter_by( id=bookIDPath).one() if myBookQuery != []: myBookQuery.name = messagecontent[0] session.add(myBookQuery) session.commit() self.send_response(301) self.send_header('Content-type', 'text/html') self.send_header('Location', '/books') self.end_headers() if self.path.endswith("/delete"): bookIDPath = self.path.split("/")[2] myBookQuery = session.query(Book).filter_by( id=bookIDPath).one() if myBookQuery: session.delete(myBookQuery) session.commit() self.send_response(301) self.send_header('Content-type', 'text/html') self.send_header('Location', '/books') self.end_headers() if self.path.endswith("/books/new"): ctype, pdict = cgi.parse_header( self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile, pdict) messagecontent = fields.get('newBookName') # Creating a new Book category Item newBook = Book(name=messagecontent[0]) session.add(newBook) session.commit() self.send_response(301) self.send_header('Content-type', 'text/html') self.send_header('Location', '/books') self.end_headers() except: pass
def newBook(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # When post, add new book newBook = Book(name=request.form['name'], user_id=login_session['user_id']) session.add(newBook) flash('New Book %s Successfully Created' % newBook.name) session.commit() return redirect(url_for('showBooks')) else: return render_template('newBook.html')
def newBook(): if request.method == 'POST': newBook = Book(sb_id=request.form['sbid'], name=request.form['name'], author=request.form['author'], subject=request.form['subject']) session.add(newBook) session.commit() flash('Book "%s" added' % newBook.name) return redirect(url_for('showBooks')) else: return render_template('newbook.html', username=login_session['username'])
def newBook(): if request.method == 'POST': if request.form['name'] and request.form['author']: newBook = Book(title=request.form['name'], author=request.form['author'], genre=request.form['genre']) session.add(newBook) session.commit() flash('New book added') return redirect(url_for('showBooks')) else: flash('Need to enter at least Title and Author of the book') return redirect(url_for('showBooks'))
def post(self): data = json.loads(request.data) print("data--------", data) title = data.get("title", None) author = data.get("author", None) genre = data.get("genre", None) if title is None or author is None or genre is None: return jsonify( {"message": "Any one from title, author, genre is missing"}) else: addedbook = Book(title=title, author=author, genre=genre) session.add(addedbook) session.commit() return jsonify(Book=addedbook.serialize)