def update(self, *args): try: book: Book = Book() if len(args) == 0: raise Exception('Invalid arguments') if isinstance(args[0], int) or isinstance(int(args[0]), int): book.fill() book.book_id = args[0] values = book.getValues().split(',') old_values = self.getById(args[0]).getValues().split(',') keys = book.getKeys().split(',') for i in range(len(keys)): if values[i] == 'null': book.__setattr__(keys[i], old_values[i]) if isinstance(args[0], Book): book = args[0] if not book.isFull(): raise Exception('Invalid input') queryStr = '' keys = book.getKeys().split(',') values = book.getValues().split(',') for i in range(len(keys)): if i == 0: continue queryStr += keys[i] + ' = ' + values[i] + ', ' str = f'Update public.\"Books\" Set {queryStr[:-2]} Where book_id = {book.book_id}' self.db.cursor.execute(str) self.db.connect.commit() return True except Exception as err: print("Update error! ", err) return False
def post(self): id = self.get_argument('id', '') resource_url = self.get_argument('resource_url', '') http_client = AsyncHTTPClient() response = yield http_client.fetch("https://api.douban.com/v2/book/" + id) response = json.loads(response.body) book = None try: book = Book.objects(bid=id)[0] except Exception as ex: app_log.error(ex) book = Book(bid=id, title=response['title'], image=response['images']['large'], isbn13=response['isbn13'], publisher=response['publisher'], wcount=0, dcount=0) finally: book.save() if resource_url: self.share_network_file(book, resource_url) else: self.share_local_file(book, resource_url)
def select_all(): book_list = [] sql = "SELECT * FROM books" result = run_sql(sql) for row in result: book = Book(row["title"], row["author"]) book_list.append(book) return book_list
def create_book(): """ Creation of book """ try: data = request.get_json(force=True) # attributes validation for at in attr: if at not in data.keys(): return jsonify({"Error": str("Missing " + at)}) obj = Book() set_obj(obj, **data) storage.insert(obj) return jsonify(obj.to_dict()) except Exception: abort(404)
def search(): query = None if request.method == 'POST': query = escape(request.form['searchinput']) else: query = escape(request.args.get('searchinput')) if query is None or len(query) == 0: redirect(url_for('home')) print("%s" % (query)) query_string = "SELECT * from \"books\" where {} ILIKE '%{}%'" isbnQuery = query_string.format("isbn", query) titleQuery = query_string.format("title", query) authorQuery = query_string.format("author", query) isbnMatchList = db.execute(isbnQuery).fetchall() titleMatchList = db.execute(titleQuery).fetchall() authorMatchList = db.execute(authorQuery).fetchall() totalList = [] for item in isbnMatchList: book = Book(item.id, item.isbn, item.title, item.author, item.year) totalList.append(book) for item in titleMatchList: book = Book(item.id, item.isbn, item.title, item.author, item.year) totalList.append(book) for item in authorMatchList: book = Book(item.id, item.isbn, item.title, item.author, item.year) totalList.append(book) uniqueList = set(totalList) for book in uniqueList: print("%s, %s, %s, %s, %s" % (book.id, book.isbn, book.title, book.author, book.year)) if len(uniqueList) == 0: return render_template("results.html", noMatches=True) else: return render_template("results.html", bookList=uniqueList)
def getAll(self, page: int, per_page: int): items = [] try: page -= 1 self.db.cursor.execute( f'SELECT {Book().getKeys()} FROM public.\"Books\" ORDER BY book_id LIMIT {per_page} OFFSET {page * per_page}' ) records = self.db.cursor.fetchall() for record in records: tmpItem = Book() tmpItem.parse(record) items.append(tmpItem) except Exception as err: print("Get error! ", err) return items
def add(self, *args): try: newEntity: Book = Book() if len(args) > 0 and isinstance(args[0], Book): newEntity = args[0] else: newEntity.fill() if newEntity.isFull(): self.db.cursor.execute( f'INSERT INTO public.\"Books\" ({newEntity.getKeys()}) ' f'VALUES ({newEntity.getValues()}) RETURNING book_id') self.db.connect.commit() return int(self.db.cursor.fetchone()[0]) except Exception as err: print("Add error! ", err) return False
def getById(self, bookId): book = Book() try: if isinstance(bookId, int): bookId = str(bookId) if not isinstance(bookId, str): raise Exception('Incorrect arguments') self.db.cursor.execute( f'SELECT {book.getKeys()} from public.\"Books\" WHERE book_id = {bookId}' ) record = self.db.cursor.fetchone() if record is not None: book.parse(record) else: raise Exception(f'No entry with ID {bookId} found') except Exception as err: print("Get by id error! ", err) return book
import pdb from models.author import Author from models.books import Book import repositories.author_repository as author_repository import repositories.book_repository as book_repository book_repository.delete_all() author_repository.delete_all() author1 = Author("George", "Martin") author_repository.save(author1) author2 = Author("Ken", "Davis") author_repository.save(author2) book1 = Book("Game of Thrones", author1) book_repository.save(book1) book2 = Book("One Flew Over the Cuckoo's Nest", author2) book_repository.save(book2) book3 = Book("Storm of Swords", author1) book_repository.save(book3) author_repository.select_all()
def book(book_app): b = Book(title="For del", author="for_del") book_app.create_object(b) return b
def add_book(): book = Book(u"侧记", "zh-CN", 1.12, 0, "学诚大和尚的生平事迹") db.session.add(book) db.session.commit()
def add_book(): if request.method == 'GET': if 'logged_in' not in session: message_body = 'You are not logged in.' message_title = 'Error!' return render_template('message.html', message_title=message_title, message_body=message_body) else: form = BookForm() return render_template('add_book.html', form=form, error=form.errors) else: form = BookForm() if form.radio.data == 'book': del form.issue del form.title_of_magazine if form.validate_on_submit(): tmp_authors = [[form.first_name.data, form.surname.data], [form.first_name_1.data, form.surname_1.data], [form.first_name_2.data, form.surname_2.data], ] new_authors = [] for first_name, surname in tmp_authors: if first_name is not '' and surname is not '': author = Author.query.filter_by(first_name=first_name, last_name=surname ).first() if not author: new_author = Author( first_name=first_name, last_name=surname ) new_authors.append(new_author) db.session.add(new_author) db.session.commit() else: new_authors.append(author) tmp_tag = Tag.query.filter_by(name=form.tag.data).first() if not tmp_tag: new_tag = Tag( name=form.tag.data ) db.session.add(new_tag) db.session.commit() else: new_tag = tmp_tag new_book = Book( title=form.title.data, table_of_contents=form.table_of_contents.data, language=form.language.data, category=form.category.data, tags=[new_tag], description=form.description.data, isbn=form.isbn.data, authors=new_authors, original_title=form.original_title.data, publisher=form.publisher.data, pub_date=datetime(year=int(form.pub_date.data), month=1, day=1)) if book_exists(new_book): message_body = 'This book already exists.' message_title = 'Oops!' return render_template('message.html', message_title=message_title, message_body=message_body) db.session.add(new_book) db.session.commit() message_body = 'The book has been added.' message_title = 'Success!' return render_template('message.html', message_title=message_title, message_body=message_body) return render_template('add_book.html', form=form, error=form.errors) if form.radio.data == 'magazine': del form.publisher del form.original_title del form.isbn del form.title if form.validate_on_submit(): tmp_tag = Tag.query.filter_by(name=form.tag.data).first() if not tmp_tag: new_tag = Tag( name=form.tag.data ) db.session.add(new_tag) db.session.commit() else: new_tag = tmp_tag new_magazine = Magazine( title=form.title_of_magazine.data, table_of_contents=form.table_of_contents.data, language=form.language.data, category=form.category.data, tags=[new_tag], description=form.description.data, year=datetime(year=int(form.pub_date.data), month=1, day=1), issue=form.issue.data) db.session.add(new_magazine) db.session.commit() message_body = 'The magazine has been added.' message_title = 'Success!' return render_template('message.html', message_title=message_title, message_body=message_body) return render_template('add_book.html', form=form, error=form.errors)
import pytest from models.books import Book test_data = [Book(title = "New Book", author = "Super Author"), Book(title = "0", author = "1")] @pytest.mark.parametrize('book', test_data, ids=[repr(b) for b in test_data]) def test_create_book(book_app, book): response = book_app.create_object(book) assert response.status_code == 201 assert response.json() == book.get_dict_with_id() #def test_create_book_without_author(book_app): # book = Book(title = "New Book") # response = book_app.create_object(book) # assert response.status_code == 201 # assert response.json() == book.get_dict_with_id() # self.assertEqual(response.status_code, 201) # self.assertEqual(response.json(), book.get_dict_with_id()) # self.client.get_book(book)
def test_create_a_book(): book = Book(name="Educated", published_date=date(2018, 1, 1), authors=[Author()], categories=[Category()], publisher=Publisher())
authors = mydb["authors"] editors = mydb["editors"] nunn = Author(authors, "John", "Nunn") print(nunn.__str__()) deFirmian = Author(authors, "Nick", "de Firmian") deFirmian.birthdate = datetime.fromisoformat('1957-07-26') print(deFirmian.toDictionary()) deFirmian.save() batsford = Editor(editors, "023567", "Batsford") print(batsford.__str__()) batsford.save() bmco = Book(books, "147963", "Batsford's Modern chess openings") bmco.addAuthor(deFirmian._id) bmco.editor = batsford._id print(bmco.__str__()) bmco.save() batsford.addBook(bmco._id) batsford.save() deFirmian.addBook(bmco._id) deFirmian.save() mco = Book(books, "258741", "Modern Chess Opening") rhpg = Editor(editors, "231854", "Random House Puzzles & Games") rhpg.save() mco.editor = rhpg._id mco.addAuthor(deFirmian._id) mco.save()
def book(app): b = Book(title="For del", author="For del") r = app.create_object(b) return(b)
more = input("Continue? (y/n) ") if more == "n": break except ValueError: break while True: try: publisher_id = int(input("Publisher ID: ")) publisher = Publisher.find(by=Publisher.id == publisher_id) break except ValueError: continue published_date = date_input("Published Date (yyyy-mm-dd): ") Book(name=name, published_date=published_date, authors=authors, categories=categories, publisher=publisher).save() elif selection == 2: display_list(of=Book) else: delete(what=Book, by=Book.id == int(input("Book ID: "))) elif selection == 3: selection = crud_menu("category") clear_screen() if selection == 1: name = input("Name: ") try: Category(name=name).save() except IntegrityError: print(f"{name} exists")