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 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 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 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 get(self): tag = self.get_arguments('tag')[0].decode() books = Book.objects() if tag == 'shared': books = [book for book in books if book.files] elif tag == 'waiting': books = [book for book in books if not book.files] elif tag == 'hot': books = Book.objects().order_by('-wcount')[:20] self.render( "book/books.html", page_heading=tag, books=books, groups=self.get_groups() )
def book_from_open_lib_result(self, result: Dict, image_size: CoverSize) -> Book: clean_result = {} source_id = result.get('key', None).split('/')[-1] cover_id = result.get('cover_i', None) isbns = result.get('isbn', []) title = result.get('title', None) author_names = result.get('author_name', []) publish_years = result.get('publish_year', []) clean_result['source_id'] = source_id clean_result['source'] = 'open library' clean_result['title'] = title.title() clean_result['author_name'] = author_names.pop( 0).title() if author_names else None clean_result['publish_year'] = publish_years.pop( 0) if publish_years else None if cover_id: clean_result['cover_url'] = self.get_cover_by_id( id=cover_id, id_type=IdType.COVER_ID, size=image_size) elif isbns: clean_result['cover_url'] = self.get_cover_by_id( id=isbns[0], id_type=IdType.ISBN, size=image_size) else: clean_result['cover_url'] = None return Book.from_dict(clean_result)
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 get(self, bookid): book = Book.objects(bid=bookid)[0] self.render( "book/preview.html", page_heading=book['title'], book=book, groups=self.get_groups() )
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
def add_book(): title = request.forms.get("title") author = request.forms.get("author") year = request.forms.get("year") desc = request.forms.get("desc") new_book_dict = {} if (title): new_book_dict["title"] = title if (author): new_book_dict["author"] = author if (year): new_book_dict["year"] = int(year) if (desc): new_book_dict["desc"] = desc new_book = Book(**new_book_dict) new_book.save() redirect('/')
def getBook(book_id): book = Book.findById(book_id) # DELETE Method Override if request.query.get('_method') == "DELETE": delete_book(book_id) if book: return template('show_book', book=book) abort(404)
def get(self): result = {} hot_books = Book.objects().order_by('-wcount')[:12] query_books = Book.objects().order_by('-update_at') rows = int(len(query_books) / 4) for row in xrange(rows): offset = row * 4 result[row] = query_books[offset:offset + 4] self.render( "home.html", page_heading='PDFLabs', rows=rows, hot_books=hot_books, groups=self.get_groups(), result=result )
def post(self, id): book = Book.objects(bid=id)[0] user = self.get_curent_user_model() if user not in book.likes: book.likes.append(user) else: book.likes.remove(user) book.save()
def check_out(book_id): username = request.forms.get("username") book = Book.findById(book_id) if (username and book): book.check_out(username) redirect('/books/%i'%book_id) if (book): abort(403) abort(404)
def get(self, id): self.set_header('Content-Type', 'application/json') http_client = AsyncHTTPClient() response = yield http_client.fetch("https://api.douban.com/v2/book/" + id) book = Book.objects(bid=id).first() book_details = json.loads(response.body) book.image = book_details.get('image') book.save() self.write(book_details)
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 get(self, id): user = User.objects(id=id)[0] books = Book.objects(likes__in=[user]) bgs = self.grouped(books) kwargs = { "page_heading": unicode(user.name), "groups": self.get_groups(), "user": user, "books": books, "bgs": bgs } self.render('user.html', **kwargs)
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 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 post(self, bookid): resource_url = self.get_argument('resource_url', None) if resource_url: try: book = Book.objects(bid=bookid)[0] except Exception as ex: app_log.error(ex) else: user = self.get_curent_user_model() file = File(file_type='network_disk', file_address=resource_url, ) file.author = user book.files.append(file) book.update_at = datetime.datetime.now() book.save() self.redirect("/book/" + bookid)
def get(self, id): book = Book.objects(bid=id)[0] params = { 'book': book, "groups": self.get_groups(), "page_heading": book.title, "like": "-empty" } try: user = self.get_curent_user_model() params['user'] = user if user in book.likes: params['like'] = "" except Exception as ex: app_log.exception(ex) self.render("book/book.html", **params)
def get(self, id): book = Book.objects(bid=id)[0] params = { 'book': book, "groups": self.get_groups(), "page_heading": book.title, "like": "-empty" } try: user = self.get_curent_user_model() params['user'] = user if user in book.likes: params['like'] = "" except Exception as ex: app_log.exception(ex) self.render("book/book.html", **params)
def book_from_google_books_result(result: Dict) -> Book: clean_result = {} info = result.get('volumeInfo') publish_year = info.get('publishedDate', None) image_links = info.get('imageLinks', None) clean_result['source_id'] = result.get('id', None) clean_result['source'] = 'google books api' clean_result['title'] = info.get('title', None) clean_result['author_names'] = info.get('authors', []) clean_result['publish_year'] = int( publish_year.split('-')[0].replace('*', '')) if publish_year else None clean_result['cover_url'] = image_links.get( 'thumbnail', None) if image_links else None return Book.from_dict(clean_result)
def post(self, bookid): resource_url = self.get_argument('resource_url', None) if resource_url: try: book = Book.objects(bid=bookid)[0] except Exception as ex: app_log.error(ex) else: user = self.get_curent_user_model() file = File( file_type='network_disk', file_address=resource_url, ) file.author = user book.files.append(file) book.update_at = datetime.datetime.now() book.save() self.redirect("/book/" + bookid)
def post(self, bookid): image = self.get_argument('images[large]') title = self.get_argument('title') isbn13 = self.get_argument('isbn13') bid = self.get_argument('id') publisher = self.get_argument('publisher') try: book = Book.objects(bid=bookid)[0] except Exception, e: app_log.error(e) book = Book(bid=bid, title=title, image=image, isbn13=isbn13, publisher=publisher, wcount=0, dcount=0 )
def edit_book(book_id): book = Book.findById(book_id) if book: title = request.forms.get("title") author = request.forms.get("author") year = request.forms.get("year") desc = request.forms.get("desc") new_book_dict = {} if (title): new_book_dict["title"] = title if (author): new_book_dict["author"] = author if (year): new_book_dict["year"] = int(year) if (desc): new_book_dict["desc"] = desc for field, value in new_book_dict.items(): book.__dict__[field] = value book.save() redirect('/books/%i' % book_id) abort(404)
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 add_book(): book = Book(u"侧记", "zh-CN", 1.12, 0, "学诚大和尚的生平事迹") db.session.add(book) db.session.commit()
def book(book_app): b = Book(title="For del", author="for_del") book_app.create_object(b) return b
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)
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 test_create_a_book(): book = Book(name="Educated", published_date=date(2018, 1, 1), authors=[Author()], categories=[Category()], publisher=Publisher())
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")
from bottle import * from models.books import Book books_app = Bottle() test = Book(title="Hitchhiker's guide to the Webdev") test.save() test2 = Book(title="Lord of the Webdev") test2.save() test3 = Book(title="Webdev: the Good Parts") test3.save() @books_app.route('/') def listBooks(): # DELETE Method Override if request.query.get('_method') == "DELETE": clear_library() return template('books_list', books=Book.find()) @books_app.route('/author/<author_name>') def showFromAuthor(author_name): return template('books_list', books=Book.find({"author":author_name})) @books_app.route('/year/<pub_year:int>') def showFromAuthor(pub_year): return template('books_list', books=Book.find({"year":pub_year})) @books_app.route('/<book_id:int>') def getBook(book_id): book = Book.findById(book_id) # DELETE Method Override
def listBooks(): # DELETE Method Override if request.query.get('_method') == "DELETE": clear_library() return template('books_list', books=Book.find())
def showFromAuthor(author_name): return template('books_list', books=Book.find({"author":author_name}))
def showFromAuthor(pub_year): return template('books_list', books=Book.find({"year":pub_year}))
def delete_book(book_id): book = Book.findById(book_id) if book: book.delete() redirect('/') abort(404)
def get(self, bookid): book = Book.objects(bid=bookid)[0] self.render("book/preview.html", page_heading=book['title'], book=book, groups=self.get_groups())
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 book(app): b = Book(title="For del", author="For del") r = app.create_object(b) return(b)
def clear_library(): Book.clear() redirect('/')