def bookin(): """ 书籍录入 输入书籍的名字,将书籍的 书名, 封面, 简介 录入数据库 """ if current_user.username == 'neo1218': form = BookForm() if form.validate_on_submit(): bookname = form.bookname.data get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname resp_1 = json.loads(urlopen(get_url).read().decode('utf-8')) book_id = resp_1['books'][0]['id'] url = "https://api.douban.com/v2/book/%s" % book_id resp_2 = json.loads(urlopen(url).read().decode('utf-8')) book = Book(url=url, name=resp_2['title'], author=resp_2['author'][0], \ tag=form.tag.data, summary=resp_2['summary'], \ image=resp_2['images'].get('large'), user_id=None, end=None, \ status=False) db.session.add(book) db.session.commit() flash('书籍已录入!') return redirect(url_for('bookin')) return render_template('bookin.html', form=form) else: return redirect(url_for('home'))
def isbn(): isbn = request.args.get('isbn') book = None form = BookForm() if isbn is not None: url = 'https://app.rakuten.co.jp/services/api/BooksBook/Search/\ 20170404?applicationId=1053085901834686387&isbn=' + isbn response = requests.get(url) session.pop('_flashes', None) if 'Items' in response.json() and response.json()['Items']: book = response.json()['Items'][0]['Item'] else: flash('該当する書籍が見つかりませんでした。再度ISBNを入力してください。', 'warning') if request.method == 'POST' and book is None: isbn = form.isbn.data return redirect(url_for('register.isbn', isbn=isbn)) if request.method == 'POST' and book is not None: if form.validate_on_submit(): if 'file' in request.files \ and request.files['file'].filename != '': try: image_url = get_new_image_url(request.files['file']) except Exception as e: flash('エラーが発生しました。もう一度やり直してください。', 'warning') app.logger.exception( '%s failed to upload an image %s', g.user.username, e) return redirect(url_for('index')) else: image_url = book['largeImageUrl'] isbn = form.isbn.data title = form.title.data author = form.author.data publisher_name = form.publisher_name.data sales_date = form.sales_date.data borrower_id = None checkout_date = None data = Book(isbn, title, author, publisher_name, sales_date, image_url, borrower_id, checkout_date) db.session.add(data) db.session.commit() flash('本を登録しました。') app.logger.info('%s registered %s successfully', g.user.username, title) return redirect(url_for('index')) else: display_errors(form.errors.items) app.logger.info('%s failed to register %s', g.user.username, form.title.data) return render_template('register/isbn.html', isbn=isbn, book=book, form=form)
def editbook(request, book_id): if request.user.is_authenticated(): if request.session['user'] == 'admin': if request.method == 'GET': print(request.GET) if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data post = Book(id=book_id, title=cd['title'], about=cd['about'], timestamp=cd['timestamp']) post.save() return HttpResponseRedirect('../../books') else: ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: post = Book.objects.get(id=int(book_id)) data = {'title': post.title, 'about': post.about} post_form = BookForm(initial=data) ctx = Context({'form': post_form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: return render_to_response('app/index.html'); else: return render_to_response('app/index.html');
def add_book(): form = BookForm() if form.validate_on_submit(): if request.method == 'POST': existing_book = Book.query.filter( Book.name == form.name.data).filter( Book.author == form.author.data).first() book = Book(name=form.name.data, author=form.author.data) if (existing_book == None): book.create_time = datetime.utcnow() db.session.add(book) elif (current_user not in book.user): book.user.append(current_user) book.create_time = datetime.utcnow() else: flash('Book already exists!') return redirect(url_for('add_book')) # return redirect(url_for('add_book')) #and(existing_book.name == form.name.data and existing_book.author == form.author.data and existing_book.user_id == current_user.id)): # flash('Book already exists!') # return redirect(url_for('add_book')) db.session.commit() flash('Your book succesfully added!') return redirect(url_for('index')) return render_template("add_book.html", title='Add_book', form=form)
def edit_book(id): if User.query.get(1) == current_user: selectedBook = book.query.get_or_404(id) categories = category.query.all() form = BookForm() if form.validate_on_submit(): if form.book_img.data: uploaded_file = request.files['book_img'] filename = secure_filename(uploaded_file.filename) uploaded_file.save( os.path.join(app.config['UPLOAD_PATH_BOOK'], filename)) selectedBook.book_img = filename cat = form.category.data newCatObj = category.query.filter_by(id=cat).first() selectedBook.name = form.name.data selectedBook.description = form.description.data selectedBook.url = form.url.data selectedBook.category = newCatObj db.session.commit() return redirect(url_for('bookTable')) elif request.method == 'GET': form.name.data = selectedBook.name form.description.data = selectedBook.description form.url.data = selectedBook.url return render_template('/admin/bookAddForm.html', categories=categories, form=form, book=selectedBook) else: abort(403)
def bookAddForm(): if User.query.get(1) == current_user: categories = category.query.all() form = BookForm() if form.validate_on_submit(): uploaded_file = request.files['book_img'] filename = secure_filename(uploaded_file.filename) uploaded_file.save( os.path.join(app.config['UPLOAD_PATH_BOOK'], filename)) cat = form.category.data catObj = category.query.filter_by(id=cat).first() new_book = book(name=form.name.data, description=form.description.data, url=form.url.data, category=catObj, book_img=filename) db.session.add(new_book) db.session.commit() return redirect(url_for('bookTable')) return render_template('/admin/bookAddForm.html', categories=categories, form=form) else: abort(403)
def book_edit(id): book = Book.query.filter_by(id=id).first() author = Author.query.filter_by(id=book.author_id).first() rental = Rental.query.filter_by(id=book.rental_id).first() form = BookForm(data={ 'tittle': book.tittle, 'author': author.name, 'quantity': book.quantity, 'status': rental.status, 'csrf_token': 1234}) if request.method == "POST": if form.validate_on_submit(): all_authors_names = [] all_authors_results = Author.query.all() for author in all_authors_results: all_authors_names.append(author.name) if form.data["author"] in all_authors_names: pass else: new_author = Author(name=form.data["author"]) db.session.add(new_author) db.session.commit() author_from_form = Author.query.filter_by(name=form.data['author']).first() rental_from_form = Rental.query.filter_by(status=form.data['status']).first() book.tittle = form.data["tittle"] book.quantity = form.data['quantity'] book.author_id = author_from_form.id book.rental_id = rental_from_form.id db.session.commit() return redirect((url_for("book_list"))) return render_template("book_id.html", form=form, id=id, book=book)
def update(author_id, book_id): form = BookForm() err = '' prev_author = Author.query.get_or_404(author_id) prev_book = Book.query.get_or_404(book_id) if not form.validate_on_submit(): form.author.data = prev_author.name form.name.data = prev_book.name else: if form.author.data == prev_author.name and form.name.data == prev_book.name: print(f'from: {form.name.data} prev: {prev_book.name}') print(f'from: {form.author.data} prev: {prev_author.name}') return redirect(url_for('books')) if check_if_exist(author_name=form.author.data, book_name=form.name.data): err = 'Book with this author exist' if err == '': prev_author.name = form.author.data prev_book.name = form.name.data db.session.add(prev_book) db.session.add(prev_author) db.session.commit() return redirect(url_for('books')) return render_template( 'book_form.html', form=form, err=err, )
def new_book(): form = BookForm() if form.validate_on_submit(): publisher = db.session.query(Publishers).filter(Publishers.publishes_name==form.publisher.data).first() if publisher:#якщо таке видавництво є в базі даних publisher_id = publisher.publishers_id else:#якщо його немає publisher_id = db.session.query(Publishers).order_by(Publishers.publishers_id.desc()).first().publishers_id + 1 publisher = Publishers(publishers_id=publisher_id, publishes_name=form.publisher.data) db.session.add(publisher) # db.session.commit() category = db.session.query(Categories).filter(Categories.category_name==form.category.data).first() if category: category_id = category.category_id else: category_id = db.session.query(Categories).order_by(Categories.category_id.desc()).first().category_id + 1 category = Categories(category_id=category_id, category_name=form.category.data) db.session.add(category) # db.session.commit() author_name = db.session.query(Authors).filter(Authors.first_name==form.name_author.data).all()#отримуємо всіх авторів з таким ім'ям author_surname = db.session.query(Authors).filter(Authors.second_name==form.surname_author.data).all()#отримуємо всіх авторів з таким прізвищем author = list(set(author_name).intersection(author_surname))#отримуємо автора з таким ім'ям і прізвищем if author: author_id = author[0].author_id else: author_id = db.session.query(Authors).order_by(Authors.author_id.desc()).first().author_id + 1 author = Authors(author_id=author_id, first_name=form.name_author.data, second_name=form.surname_author.data) db.session.add(author) # db.session.commit() # date_add = form.data_added.data.split('.') book_id = db.session.query(Books).order_by(Books.book_id.desc()).first().book_id + 1 book = Books(book_id=book_id, book_name=form.name_book.data, description=form.description.data, page=form.page.data, year=form.year.data, publisher_id=publisher_id, categories_id=category_id) db.session.add(book) # db.session.add(user_book) db.session.commit() ins = autor_has_books.insert().values(book_id=book_id, author_id=author_id) db.engine.execute(ins) # flash('Your post has been created!', 'success') return redirect(url_for('home')) return render_template('new_book.html', title='New Book', form=form, legend='New Book')
def test_BookForm_handles_saving_to_a_ListOfBooks(self): list_of_books = ListfOfBooks.objects.create() form = BookForm(data={'title':'Some title', 'current_page': 11, 'total_pages': 56, }) new_book = form.save(for_list=list_of_books) self.assertEqual(new_book, Book.objects.first()) self.assertEqual(new_book.title, 'Some title') self.assertEqual(new_book.list_of_books, list_of_books)
def index(): form = BookForm(request.form) if request.method == 'POST': if form.validate_on_submit(): id = form.data['gr_id'] num_books = form.data['num_books'] recs = recommend(id, num_books) return render_template('results.html', books=recs) return render_template('get_recs.html', form=form)
def updatebook(): form = BookForm(request.form) form.author_id.choices = [(i.id, i.lastname) for i in Author.query.all()] book = Book.query.get_or_404(form.id.data) if request.method == 'POST' and form.validate(): form.populate_obj(book) db.session.commit() return redirect(url_for('index')) return render_template('error.html', form=form)
def book_list(): form = BookForm() error = "" if request.method == "POST": if form.validate_on_submit(): books.create(form.data) return redirect(url_for("books_list")) return render_template("books.html", form=form, books=books.all(), error=error)
def post(self): """ Adding new book :return: Response """ form = BookForm() if form.validate_on_submit(): author = Author(escape(form.data["name"])) db.session.add(author) db.session.commit()
def add_book(): form = BookForm() if form.validate_on_submit(): book = Book() book.book = form.name.data db.session.add(book) db.session.commit() flash("Book create with successfully!", "success") return redirect(url_for(".add_book")) return render_template("add.html", form=form)
def add_book(): form = BookForm() if request.method == 'POST' and form.validate_on_submit(): new_Book = Book(form.title.data, form.author.data, form.price.data, form.reorderthres.data, form.stock.data) db.session.add(new_Book) db.session.commit() flash('Book Successfully Added', 'success') return redirect(url_for('get_books')) return render_template("add_book.html", form=form)
def book_add(): form = BookForm() if form.validate_on_submit(): book = Book() book.name = form.name.data db.session.add(book) db.session.commit() flash("Livro cadastrado com sucesso", "success") return redirect(url_for('book.book_add')) return render_template('book/add.html', form=form)
def createbook(): form = BookForm() form.author.choices =[(c.id, c.author) for c in Author.query.all()] if form.validate_on_submit(): book = Book(author=form.author.data, title=form.title.data) db.session.add(book) db.session.commit() flash('Book by author {}, title {}'.format( form.author.data, form.title.data)) return redirect(url_for('index')) return render_template('createbook.html', title='Create book', form=form)
def add_book(): # if current_user.role != 'admin': # abort(403) form = BookForm() if form.validate_on_submit(): book = Book(book_name = form.book_name.data, book_author = form.book_author.data, book_date_publ = form.book_date_publ.data) db.session.add(book) db.session.commit() flash('Книга в базе:)', 'success') return redirect(url_for('add_book')) return render_template('books.html', title='База книг', form=form, book_get=Book.query.all())
def add_book(): form = BookForm() form.author.choices = [(i.id, i.name) for i in Author.query.all()] if form.validate_on_submit(): Book.save(name=form.name.data, date=form.date.data, author_id=form.author.data) return redirect(url_for('books')) return render_template('form.html', title="Добавление новой книги", form=form, url=url_for('add_book'))
def update(book_id): book = firestore.read(book_id) form = BookForm(data=book) # Process form if submission request if form.validate_on_submit(): data = form.data book = firestore.update(data, book_id) return redirect(url_for('app.view', book_id=book['id'])) book = firestore.read(book_id) return render_template('book_form.html', form=form, header="Update Book")
def update_book(bookId): errors = ["An error occurred while trying to update your book."] the_book = Book.query.get(bookId) form = BookForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): the_book.update_title(form.data['title']) db.session.add(the_book) db.session.commit() return {"book": the_book.to_dict()} return {"errors": errors}
def form(request): form=BookForm(request.POST) if request.method=="POST": if form.is_valid(): print(request.POST) Book.objects.create(bname=request.POST.get('bname'),bauthor=request.POST.get('bauthor'),bprice=request.POST.get('bprice')) return HttpResponseRedirect('/forms/') #form=BookForm() if form.errors: formerror=form.errors book = Book.objects.all() return render(request,'app/forms.html',{'form':form,'book':book,'formerror':formerror})
def addBook(): form = BookForm() if form.validate_on_submit(): book = Book(title=form.title.data, writer=form.writer.data, link=form.link.data, pages=form.pages.data, finished=form.finished.data, user_id=current_user.id) db.session.add(book) db.session.commit() return redirect(url_for('home')) return render_template('book_form.html', form=form)
def create_new_book(): errors = ["Error creating a new book."] form = BookForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): new_book = Book(the_title=form.data['title'], creator_id=current_user.get_id()) db.session.add(new_book) db.session.commit() return {"book": new_book.to_dict()} return {"errors": errors}
def update_book(bookid): form = BookForm() book = Book.query.get(bookid) if request.method == 'POST' and form.validate_on_submit(): form.populate_obj(book) db.session.commit() flash('Book Successfully Updated', 'success') return redirect(url_for('get_books')) return render_template("update_book.html", form=form, book=book) #new_Book = Book(data['title'], data['author'], data['price'], data['reorderthres'], data['stoporder'], data['stock']) db.session.commit() return render_template("add_book.html", form=form)
def book_details(book_id): book = books.get(book_id - 1) form = BookForm(data=book) if request.method == "POST": if request.form.get('delete'): books.delete(book_id - 1) elif form.validate_on_submit(): if book_id > 0: books.update(book_id - 1, form.data) else: pass return redirect(url_for("books_list")) return render_template("book.html", form=form, book_id=book_id)
def test_validation_for_blank_book_details_input(self): form = BookForm(data={'title':'', 'current_page': 45, 'total_pages': 500, }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['title'], [EMPTY_INPUT_ERROR]) form = BookForm(data={'title':'Some title', 'current_page': '', 'total_pages': '', }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['current_page'], [EMPTY_INPUT_ERROR]) form = BookForm(data={'title':'Some title', 'current_page': 20, 'total_pages': '', }) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['total_pages'], [EMPTY_INPUT_ERROR])
def add(): """Add a new book to the firestore database Return user to the view page for the new book""" form = BookForm() if form.validate_on_submit(): data = form.data # Processs image if there is one # COME BACK book = firestore.create(data) return redirect(url_for('app.view', book_id=book['id'])) return render_template('book_form.html', form=form, header="Add Book")
def viewList(request, list_of_books_id): labels = [] data = [] list_of_books = ListfOfBooks.objects.get(id=list_of_books_id) list_of_books_set_for_chart = Book.objects.filter( list_of_books=list_of_books) for book in list_of_books_set_for_chart: labels.append(book.title) percentage = round(book.current_page / book.total_pages * 100, 2) data.append(percentage) form = ExisitingBooksInList(for_list=list_of_books, owner=request.user) if request.method == 'POST': form = ExisitingBooksInList(for_list=list_of_books, owner=request.user, data=request.POST) if form.is_valid(): form = None form = BookForm(data=request.POST) form = form.save(for_list=list_of_books) form.owner = request.user form.save() return redirect(list_of_books) return render( request, 'list.html', { 'labels': labels, 'data': data, 'list_of_books': list_of_books, 'form': form, })
def put(self, book_id): form = BookForm() if form.validate_on_submit(): book = Book.query.get(book_id) book.title = escape(form.data['title']) # escape() is overkill here authors = [Author.query.filter_by(name=escape(submitted_artist_name)).first() for submitted_artist_name in request.json["authors"] ] # remove all nonexistent objects (they are not in DB) authors = list(filter(None, authors)) # FIXME: Old M2M relations is not removed. Refactoring needed book.authors = authors db.session.commit()
def myList(request): list_of_books_set_for_chart = Book.objects.filter(owner=request.user) books_set_ID = [] list_of_books_set_ID = [] for i in list_of_books_set_for_chart: books_set_ID.append(i.id) list_of_books_set_ID.append(i.list_of_books_id) labels = [] data = [] if list_of_books_set_ID != []: for book in list_of_books_set_for_chart: labels.append(book.title) percentage = round(book.current_page / book.total_pages * 100, 2) data.append(percentage) list_of_books = ListfOfBooks.objects.get(id=list_of_books_set_ID[0]) form = ExisitingBooksInList(for_list=list_of_books, owner=request.user) if request.method == 'POST': form = ExisitingBooksInList(for_list=list_of_books, owner=request.user, data=request.POST) if form.is_valid(): form = None form = BookForm(data=request.POST) form = form.save(for_list=list_of_books) form.owner = request.user form.save() return redirect(list_of_books) else: messages.error(request, DUPLICATE_INPUT_ERROR) form = ExisitingBooksInList(for_list=list_of_books, owner=request.user) return render( request, 'myList.html', { 'labels': labels, 'data': data, 'list_of_books': list_of_books, 'form': form, }) else: return render(request, 'home.html', {'form': BookForm()})
def new_entry(request): if request.session['user'] == 'admin': if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data print(cd) post = Book(title=cd['title'], about=cd['about'], timestamp=cd['timestamp']) post.save() return HttpResponseRedirect('/books.html') else: ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: form = BookForm() ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: return render_to_response('app/index.html');
def bookin(): """ 书籍录入 输入书籍的名字,将书籍的 书名, 封面, 简介 录入数据库 """ if current_user.username == "neo1218": form = BookForm() if form.validate_on_submit(): bookname = form.bookname.data get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname resp_1 = json.loads(urlopen(get_url).read().decode("utf-8")) book_id = resp_1["books"][0]["id"] url = "https://api.douban.com/v2/book/%s" % book_id resp_2 = json.loads(urlopen(url).read().decode("utf-8")) book = Book( url=url, name=resp_2["title"], author=resp_2["author"][0], tag=form.tag.data, summary=resp_2["summary"], image=resp_2["images"].get("large"), user_id=None, end=None, status=False, ) db.session.add(book) db.session.commit() flash("书籍已录入!") return redirect(url_for("bookin")) return render_template("bookin.html", form=form) else: return redirect(url_for("home"))