def put(self, _id): json_data = request.get_json(force=True) book = Book.query.filter_by(id=_id).first() publisher = Publisher.query.filter_by( name=json_data['publisher_name']).first() publisher_id = publisher.id genre = Genre.query.filter_by(name=json_data['genre_name']).first() genre_id = genre.id book = Book(json_data['title'], json_data['picture_url'], json_data['hyperlink'], genre_id, publisher_id) status = 200 if book: book.title = json_data['title'] book.picture_url = json_data['picture_url'] book.hyperlink = json_data['hyperlink'] book.genre_id = genre_id book.publisher_id = publisher_id book.commit() else: book = Book(json_data['title'], json_data['picture_url'], json_data['hyperlink'], genre_id, publisher_id) status = 201 book.save() return book.json(), status
def setUp(self): super(TestBook, self).setUp() self.maxDiff = None self.app = create_app() self.session = session user_obj = User(username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass")) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id) book_type = BookType(book_type="normal", charge="1.5") self.session.add(book_type) self.session.flush() self.book_type_id = int(book_type.id) book_type = BookType(book_type="fiction", charge="3") self.session.add(book_type) self.session.flush() self.book_type_id_1 = int(book_type.id) book_obj = Book(book_name="python", book_type_id=self.book_type_id) self.session.add(book_obj) self.session.flush() self.book_id = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=self.book_type_id_1) self.session.add(book_obj) self.session.flush() self.book_id_2 = int(book_obj.id) user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=self.book_id) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=self.book_id_2) self.session.add(user_book_mapping) self.session.flush()
def book_list(): books = [ Book('Python Flask', 59.00, 'Eason', '人民邮电出版社'), Book('Python Selenium', 59.00, 'Tom', '人民邮电出版社'), Book('Python 爬虫', 39.00, 'Eason', '北京大学出版社'), Book('Python 多线程', 49.00, 'Eason', '清华大学出版社'), Book('Python 语言', 29.00, 'Eason', '人民邮电出版社') ] return render_template('book-list.html', books=books)
def test_get_number_of_books_charge_on_basis_of_story_3(self): with self.app.app_context(): self.session.rollback() user_obj = User(username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass")) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id) book_type = BookType(book_type="normal", charge="1.5", fixed_days=2, fixed_charges=2) self.session.add(book_type) self.session.flush() book_type_id_1 = int(book_type.id) book_type = BookType(book_type="fiction", charge="3") self.session.add(book_type) self.session.flush() book_type_id_2 = int(book_type.id) book_type = BookType(book_type="novel", charge="1.5", fixed_days=3, fixed_charges=4.5) self.session.add(book_type) self.session.flush() book_type_id_3 = int(book_type.id) book_obj = Book(book_name="python", book_type_id=book_type_id_1) self.session.add(book_obj) self.session.flush() book_id_1 = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=book_type_id_2) self.session.add(book_obj) self.session.flush() book_id_2 = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=book_type_id_3) self.session.add(book_obj) self.session.flush() book_id_3 = int(book_obj.id) user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_1) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_2) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_3) self.session.add(user_book_mapping) self.session.flush() response = get_number_of_books_charge(user_id=self.user_id) self.assertEqual(response, dict(book_charges=9.5, number_of_books=3))
def find_book(self) -> Book: books = Book().select().where(Book.title.contains(input('Szukaj tytułu: '))) for book in books: print(f'{book.id} | {book.title}') if not books: self.find_book() while True: try: return Book().get_by_id(int(input('Wybierz książkę'))) except: print('Nie wybrano książki....')
def create_book(): book_list = book_repository.select_all() for book in book_list: if book.author.name == request.form["author"]: new_book = Book(request.form["title"], book.author) book_repository.save(new_book) return else: new_author = Author(request.form["author"]) author_repository.save(new_author) new_book = Book(request.form["title"], new_author) book_repository.save(new_book) return redirect("/books")
def setUp(self): db.create_all() author1 = Author('Matt') author2 = Author('Elie') tag1 = Tag('Sci Fi') tag2 = Tag('Horror') tag3 = Tag('Biography') db.session.add_all([author1, author2, tag1, tag2, tag3]) db.session.commit() book1 = Book('Night of the Living Decorator', author2.id) book1.tags = [tag2] book2 = Book("Matt's Scary Sci Fi book", author1.id) book2.tags = [tag1, tag2] db.session.add_all([book1, book2]) db.session.commit()
def add(self): print('Dodawanie książki') print('-----------------') title = input('Tytuł:') isbn = input('ISBN(13):') description = input('Opis (opcjonalnie):') publisher = Publisher().get_or_create( name=input('Nazwa wydawnictwa: '))[0] # pętla do dodawania autoróœ next_author = 't' authors = [] while next_author == 't': authors.append(input("Imię i nazwisko autora: ")) next_author = input('Następny autor? [t/n]') authors = self.add_authors(authors) book = Book(title=title, isbn=isbn, description=description, publisher=publisher) book.save() book.authors = authors book.update() return book.id
def import_to_database(database_url, file): with open(file, "r") as csvDataFile: reader = csv.DictReader(csvDataFile, delimiter=',') book = None bulk_insert = "INSERT INTO book (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)" data = [] for row in reader: #print(row) book = Book(row['isbn'], row['title'], row['author'], row['year']) if book.is_valid(): data.append({ "isbn": book.isbn, "title": book.title, "author": book.author, "year": book.year }) else: print(f"Could not INSERT {book.isbn}") #print(data) db.execute(bulk_insert, data) db.commit()
def post(self): #parse json from request body book_data = json.loads(self.request.body) #missing post body information will raise exception, so we need to use try try: book = Book(title=book_data['title'], isbn=book_data['isbn'], parent=Book.parent_key()) except: #if creating the book failed, it's most likely due to missing data is post body #so just return 'bad request' and exit self.response.set_status(400) return #add optional keys, if they are sent in request body for optional_key in ['checkedIn', 'genre']: if optional_key in book_data: setattr(book, optional_key, book_data[optional_key]) #save book in datastore book.put() #Set HTTP status code to 'created' self.response.set_status(201) #return json values of newly created book self.write_json(book.to_json())
def add_book(): if request.method == "GET": return render_template("books/add.html") book_title = request.form.get("book-title") book_author = request.form.get("book-author") if not book_title: raise BadRequest("Field 'Title' is required!") # raise BadRequest("Field 'book-title' is required!") elif not book_author: raise BadRequest("Field 'Author' is required!") book = Book(title=book_title, author=book_author) db.session.add(book) try: db.session.commit() except IntegrityError: log.exception("Couldn't add book, git integrity error") db.session.rollback() raise BadRequest( "Error adding new book, probably the title is not unique") except DatabaseError: log.exception("Could not add book, got database error") db.session.rollback() raise InternalServerError("Error adding new book") url = url_for("books_app.details", book_id=book.id) return redirect(url)
def add_book(): if request.method == 'GET': return render_template('add_book.html') elif request.method == 'POST': authors = [ author.strip() for author in request.form['book_authors'].split(',') ] title = request.form['book_title'] genre = request.form['book_genre'] isbn = request.form['book_isbn'] date = request.form['book_date'] if authors is not None and title != '' and genre != '' and isbn != '' \ and date != '': book = Book(None, isbn, genre, title, date) book.add_book(authors) return redirect(url_for('books')) elif title == "": return render_template('add_book.html', error='Title is reuqered!') elif genre == "": return render_template('add_book.html', error='Genre is reuqered!') elif isbn == "": return render_template('add_book.html', error='ISBN is reuqered!') elif date == "": return render_template('add_book.html', error='Date is reuqered!') elif authors is None: return render_template('add_book.html', error='''At least one author is requred!''')
def load_database(iris_native): book_db = data['database'] iris_native.kill(book_db) book_list = [] with open('data/books.csv') as f: lines = f.readlines() for line in lines: book_list.append(line.strip('\n')) for i in range(1, len(book_list)): book = Book() book_info = book_list[i] book_info = book_info.split(',') book.title = book_info[0] book.author = book_info[1] book.publisher = book_info[2] book.page_count = book_info[3] book.pic_url = book_info[4] book.available = True iris_native.set(book.title, book_db, i, "title") iris_native.set(book.author, book_db, i, "author") iris_native.set(book.publisher, book_db, i, "publisher") iris_native.set(book.page_count, book_db, i, "page_count") iris_native.set(book.pic_url, book_db, i, "pic_url") iris_native.set(book.available, book_db, i, "available") print("Loaded books into database")
def add(self): name = self.get_argument('bookname', None) source = self.get_argument('source', None) author = self.get_argument('author', None) price = float(self.get_argument('price', 0)) upload = int(self.get_secure_cookie('sign')) breif = self.get_argument('breif', None) if not name or not source or not author: self.reply_json_error(1, u'请填写书名,来源或者作者') return b = Book.select(Book.q.bookName == name).count() if b: self.reply_json_error(1, u'本书已经存在,请勿重复添加') return try: book = Book(bookName=name, source=source, author=author, uploadUser=upload, price=price, bookDesc=breif) if book: self.reply_json_data(0, u'书籍添加成功') return else: self.reply_json_error(1, u'书籍添加失败!') return except Exception as e: app_log.error(str(e))
def rating_book_request_impl(args): try: book_name = args['book_name'] author_name = args['author_name'] category_name = args['category_name'] rating = args['rating'] if len(book_name) == 0: raise InvalidBookNameException if rating < 0 or rating > 5: raise InvalidRatingException book = find_book_with_name(book_name) if book is None: book = Book(book_name, author_name, category_name) db.session.add(book) rating = Rating(rating, book) db.session.add(rating) book.ratings.append(rating) db.session.commit() return Response(True, "Book Rating Done", BookSchema().dumps(book).data).output() except Exception as e: return json.dumps({"error": str(e)})
def get_books(self, term, limit=5): current_url = self.url + '/volumes?' + 'q=' + term + '&maxResults=' + str( limit) data = self.client.request('GET', current_url) items = data.get('items') if not items: return [] return [Book(i, data).json() for i, data in enumerate(items)]
def add(): form = request.form book = Book() book.from_form(form) if Book.has_book(book.title) is False: log("save to database") book.save() return redirect(url_for('.index'))
def create_book(): title = request.form["title"] author_id = request.form["author_id"] author = author_repository.select(author_id) book = Book(title, author) book_repository.save(book) return redirect("/books")
def create_book(): title = request.form['title'] genre = request.form['genre'] publisher = request.form['publisher'] author = author_repository.select(request.form['author_id']) book = Book(title, genre, publisher, author) book_repository.save(book) return redirect("/books")
def update_book(id): title = request.form['book-title'] author_id = request.form['author'] genre = request.form['genre'] publisher = request.form['publisher'] author = author_repository.select(author_id) book = Book(title, genre, publisher, author, id) book_repository.update(book) return redirect('/books')
def select(id): book = None sql = "SELECT * FROM books WHERE ID = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: book = Book(row['title'], row['publisher'], row['genre'], row['id']) return book
def create_book(): title = request.form["title"] description = request.form["description"] author_id = request.form["author"] theme = request.form["theme"] author = author_repository.select(author_id) book = Book(title, description, author, theme) book_repository.save(book) return redirect('/books')
def update_book(id): title = request.form['title'] genre = request.form['genre'] publisher = request.form['publisher'] author = author_repository.select(request.form['author_id']) book = Book(title, genre, publisher, author, id) print(book.author.full_name()) book_repository.update(book) return redirect('/books')
def select(id): book = None sql = "SELECT * FROM authors WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: book = Book(result['first_name'], result['last_name'], result['id']) return book
def select(id): book = None sql = "SELECT * FROM books WHERE id=%s" values = [id] result = run_sql(sql, values)[0] if result is not None: author = author_repository.select(result['author_id']) book = Book(result['title'], author, result['id']) return book
def update_book(id): title = request.form['title'] author_id = request.form['author_id'] description = request.form['description'] theme = request.form['theme'] author = author_repository.select(author_id) book = Book(title, description, author, theme, id) book_repository.update(book) return redirect('/books')
def select_all(): books = [] sql = "SELECT * FROM books" results = run_sql(sql) for row in results: author_id = author_repository.select(row['author_id']) book = Book(row['title'], row['genre'], row['description'], author_id, row['rating'], row['id']) books.append(book) return books
def update_book(id): title = request.form['title'] year = request.form['year'] genre = request.form['genre'] purchased = request.form['purchased'] author_id = request.form['author_id'] author = author_repository.select(author_id) book = Book(title, year, genre, purchased, author, id) book_repository.update(book) return redirect('/books')
def select_all(): books = [] sql = "SELECT * FROM books" results = run_sql(sql) for row in results: book = Book(row['title'], row['genre'], row['year'], row['id']) books.append(book) return books
def select_all(): books = [] sql = "SELECT * FROM books" results = run_sql(sql) for row in results: author = author_repository.select(row['author_id']) book = Book(row['title'], row['genre'], row['publisher'], author) books.append(book) return books