def testCanFindBooksInCategory(self): tech = Category(name='tech') book = Book(name='Clean Code', category=tech) book2 = Book(name='Eloquent JavaScript', category=tech) db.session.add_all([book, book2, tech]) db.session.commit() books = Book.query.filter_by(category=tech).all() self.assertIsNotNone(books)
def test_follow_posts(self): # create users and books u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') b1 = Book(title='Gone with the wind', author='Margaret Mitchell') b2 = Book(title='A tale of 2 cities', author='Charles Dickens') b3 = Book(title='Conspiration', author='Dan Brown') db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(u4) db.session.add(b1) db.session.add(b2) db.session.add(b3) db.session.commit() # create four posts now = datetime.utcnow() p1 = Post(body="post from john", user=u1, book=b1, timestamp=now + timedelta(seconds=1), level=1) p2 = Post(body="post from susan", user=u2, book=b2, timestamp=now + timedelta(seconds=4), level=1) p3 = Post(body="post from mary", user=u3, book=b2, timestamp=now + timedelta(seconds=3), level=1) p4 = Post(body="post from david", user=u4, book=b3, timestamp=now + timedelta(seconds=2), level=1) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(b1) u1.follow(b2) u1.follow(b3) u2.follow(b1) db.session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() self.assertEqual(f1, [p2, p3, p4, p1]) self.assertEqual(f2, [p1])
def testSearchBookByName(self): book_one = Book(name='New World Order') book_two = Book(name='Things Fall Apart') book_three = Book(name='Pinkberry') book_four = Book(name='New Scopes') db.session.add_all([book_one, book_two, book_three, book_four]) db.session.commit() self.assertEqual(len(Book.findByName('New World')), 1) self.assertEqual(len(Book.findByName('N')), 2)
def test_adding_books(self): b1 = Book(metabook_id=1, owner_id=1, condition="new", region="sf") b2 = Book(metabook_id=1, owner_id=1, condition="used", region="hyd") b3 = Book(metabook_id=1, owner_id=1, condition="torn", region="sel") db.session.add_all([b1, b2, b3]) db.session.commit() hydbook = Book.query.filter_by(region="hyd").first() numbertorn = Book.query.filter_by(condition="torn").all() self.assertEqual(hydbook.owner_id, 1) self.assertEqual(len(numbertorn), 1)
def deploy(): """Run deployment tasks.""" from flask_migrate import upgrade from app.models import Role, User, Rent, Book # migrate database to latest revision # upgrade() db.drop_all() db.create_all() # create user roles Role.insert_roles() db.session.add(Book(title="math", author="eula")) db.session.add(Book(title="physics", author="einstein")) Book.generate_fake(10)
def add_book_post(): if request.method == "POST": if not request.form['title'] or not request.form[ 'describe'] or not request.form['name'] or not request.form[ 'species']: flash('You have to enter all fields!') else: book = Book(request.form['title'], request.form['describe']) author = Authors(name=request.form.get("name")) category = Category(species=request.form.get("species")) db.session.add(book) db.session.add(author) db.session.add(category) # Pushing data to 'pivot' tables author.auth_book.append(book) category.cat_book.append(book) db.session.commit() flash('Successfully added') return render_template("add_book_post.html", book=book, author=author, category=category)
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 test_follow(self): u1 = User(username='******', email='*****@*****.**') b1 = Book(title='Gone with the wind', author='Margaret Mitchell') db.session.add(u1) db.session.add(b1) db.session.commit() self.assertEqual(u1.books.all(), []) self.assertEqual(b1.users.all(), []) u1.follow(b1) db.session.commit() self.assertTrue(u1.is_following(b1)) self.assertEqual(u1.books.count(), 1) self.assertEqual(u1.books.first().title, 'Gone with the wind') self.assertEqual(b1.users.count(), 1) self.assertEqual(b1.users.first().username, 'john') u1.unfollow(b1) db.session.commit() self.assertFalse(u1.is_following(b1)) self.assertEqual(u1.books.count(), 0) self.assertEqual(b1.users.count(), 0)
def add_book(book_name, year): book = Book(book_name, year) db.session.add(book) db.session.commit() # books = Book.query.filter(Book.id == book.id) # return db.session.query(Book).get(book.id).serialize() return db.session.query(Book).get(book.id)
def testSearchCategoryByName(self): category_one = Category(name='One') category_two = Category(name='Two') db.session.add_all([category_one, category_two]) db.session.commit() book_one = Book(name='New World Order', category=category_one) book_two = Book(name='Things Fall Apart', category=category_two) book_three = Book(name='Pinkberry', category=category_two) book_four = Book(name='New Scopes', category=category_two) db.session.add_all([book_one, book_two, book_three, book_four]) db.session.commit() self.assertEqual(len(category_one.books.all()), 1) self.assertEqual(len(category_two.books.all()), 3) self.assertEqual(len(Book.findByCategoryName(category_two.name)), 3) self.assertIsNone(Book.findByCategoryName('New Category'))
def get_added_books(delta_entries, user_id, client): """ Return a list of Books. All books in this list have the correct mimetype, are under the size limit, and don't have a duplicate hash in the database (i.e. not a filepath rename). """ added_entries = [] for entry in delta_entries: pathname, metadata = entry pathname = canonicalize(pathname) # First check that it's not a removed pathname. if metadata is None: continue # Check that pathname is a file, has an okay mimetype and is under the # size limit. if (metadata['is_dir'] or not mimetypes_filter(pathname) or metadata['bytes'] > AMAZON_SIZE_LIMIT): continue book = Book(user_id, pathname, metadata['bytes']) download_book(client, book, u'kindlebox') # Make sure that the book is not a duplicate of a previously added book # (probably a renamed file). duplicate = (Book.query.filter_by(user_id=user_id).filter_by( book_hash=book.book_hash).first()) if (duplicate is not None): book.unsent = duplicate.unsent added_entries.append(book) return added_entries
def create_api(app, swagger_host=None, swagger_port=5000): custom_swagger = { "info": {"title": "New Title"}, "securityDefinitions": {"ApiKeyAuth": {"type": "apiKey" , "in" : "header", "name": "My-ApiKey"}} } # Customized swagger will be merged api = SAFRSAPI(app, host=swagger_host, port=swagger_port, custom_swagger=custom_swagger) api.expose_object(Thing) api.expose_object(SubThing) for i in range(30): secret = hashlib.sha256(bytes(i)).hexdigest() reader = Person(name="Reader " + str(i), email="reader_email" + str(i), password=secret) author = Person(name="Author " + str(i), email="author_email" + str(i)) book = Book(title="book_title" + str(i)) review = Review( reader_id=reader.id, book_id=book.id, review="review " + str(i) ) if i % 4 == 0: publisher = Publisher(name="name" + str(i)) publisher.books.append(book) reader.books_read.append(book) author.books_written.append(book) for obj in [reader, author, book, publisher, review]: db.session.add(obj) db.session.commit() for model in [Person, Book, Review, Publisher]: # Create an API endpoint api.expose_object(model)
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 add_book(title, publish_date=date.today(), create_file=False, uploader=None, authors=None, language=None): file = f'/tmp/{title}.pdf' book = Book(title=title, publish_date=publish_date, file=file, file_type='pdf') if create_file: with open(file, 'w+') as file: file.write(title) book.set_hash() if uploader: book.uploader = uploader if language: book.language = language if authors: for author in authors: book.authors.append(author) db.session.add(book) db.session.commit()
def import_books(): data = request.get_json(force=True) validate(data, post_import_books_schema) books = [] errors = [] for item in data: err = '' book = Book.query.filter(Book.old_id == item['id']).first() if not book: book = Book(old_id=item['id'], title=item['Title'], author=item['Author'], image_filename=item['ImageFilename'], description=item['LongDesc'], price=item['Price'], buy_code=item['BuyCode']) books.append(book) dao_create_book(book) else: err = u'book already exists: {} - {}'.format( book.old_id, book.title) current_app.logger.info(err) errors.append(err) res = {"books": [b.serialize() for b in books]} if errors: res['errors'] = errors return jsonify(res), 201 if books else 400 if errors else 200
def create(request): if request.method == "GET": form = BookForms() return render(request, 'Library/book.html', {"form": form}) if request.method == "POST": form = BookForms(request.POST) if form.is_valid(): obj = Book() obj.name = form.cleaned_data["name"] obj.isbn = form.cleaned_data["isbn"] obj.published_date = form.cleaned_data["published_date"] obj.pages = form.cleaned_data["pages"] obj.save() #for e in form.cleaned_data["authors"]: obj.authors.set(form.cleaned_data["authors"]) obj.save() return render( request, 'Library/book.html', { "form": BookForms(), "msg": { "status": "success", "msg": "Se añadio el libro" } }) return render(request, 'Library/book.html', {"form": form})
def addbook(): form = AddBook() if form.validate_on_submit(): title = form.title.data author = form.author.data price = form.price.data pub_date = form.pub_date.data if title.lower() in [book.title.lower() for book in Book.query.all()]: flash('This book already exists in the store') return redirect('addbook') if author.lower() in [ auth.name.lower() for auth in Author.query.all() ]: author = Author.query.filter_by(name=author) else: author = Author(name=author) db.session.add(author) book = Book(title=title, author=author, price=price, pub_date=pub_date) db.session.add(book) db.session.commit() flash(f'{title} successfully added to the store') return redirect('index') return render_template('addbook.html', form=form)
def testBookCreation(self): book_one = Book(name='Play') self.assertIsNone(book_one.id) db.session.add(book_one) db.session.commit() self.assertIsNotNone(book_one.id) self.assertEqual(str(book_one), "<Book u'Play'>")
def get_books_for_user(token: str): user_token = session.get(token) api_url = "{0}/{1}/{2}".format(app.config['API_URL'], 'books', user_token) genre_api_url = "{0}/{1}".format(app.config['API_URL'], 'genres') resp = requests.get(api_url) data = resp.json() print(data) resp1 = requests.get(genre_api_url) data1 = resp1.json() books = [] genres = [] size = len(data) size1 = len(data1) for i in range(size): books.append( Book(data[i]['id'], data[i]['name'], data[i]['author'], data[i]['description'], data[i]['mark'])) for i in range(size1): genres.append(Genre(data1[i]['id'], data1[i]['name'])) if len(data) == 0: books = None return books, genres
def add(): form = AddBookForm() form.numbers.data = 3 if form.validate_on_submit(): new_book = Book(isbn=form.isbn.data, title=form.title.data, origin_title=form.origin_title.data, subtitle=form.subtitle.data, author=form.author.data, translator=form.translator.data, publisher=form.publisher.data, image=form.image.data, pubdate=form.pubdate.data, tags_string=form.tags.data, pages=form.pages.data, price=form.price.data, binding=form.binding.data, numbers=form.numbers.data, summary=form.summary.data or "", catalog=form.catalog.data or "") db.session.add(new_book) db.session.commit() flash(u'Book %s has been added to the library!' % new_book.title, 'success') return redirect(url_for('book.detail', book_id=new_book.id)) return render_template("book_edit.html", form=form, title=u"Add new book")
def test_book_model(self): """ Test adding a book & number of records in Book table. """ author = Author(full_name="Erenest Hemingway") additional_author = Author(full_name="My Name") category = Category(category_name="War novel") additional_category = Category(category_name="WWII") book = Book( title="For Whom the Bell Toll", description="It tells the story of Robert Jordan.", book_categories=[category], book_authors=[author], ) db.session.add(book) db.session.commit() book.book_authors.append(additional_author) book.book_categories.append(additional_category) db.session.commit() self.assertEqual(Book.query.count(), 1) self.assertEqual(Book.query.first().title, "For Whom the Bell Toll") self.assertEqual(Book.query.first().description, "It tells the story of Robert Jordan.") self.assertEqual(Book.query.first().book_categories, [category, additional_category]) self.assertEqual(Book.query.first().book_authors, [author, additional_author])
def batch_add(): if request.method == 'POST' and 'file' in request.files: file = request.files['file'] if file and file.filename[-4:] == '.csv': count = 0 datas = BytesIO(file.read()).read() encode = chardet.detect(datas)['encoding'] datas = datas.decode(encode).replace('\r\n', '\n') for l in datas.split('\n'): data = l.split(',') try: book = Book(id=int(data[0]), type=data[1], name=data[2], publisher=data[3], year=data[4], author=data[5], price=data[6], amount=data[7]) except Exception: return '<script>alert("处理行\\n'+ l + '\\n时发生问题,请检查文件!,确保以英文逗号分割。该行之前部分记录已经添加成功!"); window.location="/add";</script>' try: db.session.add(book) db.session.commit() except Exception: return '<script>alert("处理行\\n'+ l + '\\n时发生问题,添加入数据库失败,请检查数据book_id是否有重复。部分记录添加成功"); window.location="/add";</script>' count += 1 return render_template("add.html", message="添加%d套书籍成功成功!" % count) else: return render_template('add.html', message="文件不合法!") return redirect(url_for('app.view.add'))
def search(): api_key = app.config["API_KEY"] isbn = request.form.get("isbn") book = None try: url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn + "&key=" + api_key response = requests.get(url) json_obj = response.json() title = json_obj['items'][0]['volumeInfo']['title'] authors = json_obj['items'][0]['volumeInfo']['authors'][0] page_count = json_obj['items'][0]['volumeInfo']['pageCount'] rating = json_obj['items'][0]['volumeInfo']['maturityRating'] thum = json_obj['items'][0]['volumeInfo']['imageLinks']['thumbnail'] book = Book(title=title, author=authors, page_count=int(page_count), maturity_rating=rating, thumbnail=thum) except Exception as e: print("Could not find item") print(e) return render_template("search.html", title="Search Page", book=book)
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 add_book_by_isbn(): try: data = request.get_json() isbn = str(data["isbn"]) authors = str(data["authors"]) pages = str(data["pages"]) title = str(data["title"]) if len(isbn) != 10 and len(isbn) != 13: return redirect(url_for("errors.bad_request")) book = Book.query.filter_by(id=isbn).first() if not book: book = Book(id=str(isbn)) db.session.add(book) db.session.commit() book = Book.query.filter_by(id=isbn).first() book_exist = User_Book.query.filter_by(user_id=current_user.id, book_id=isbn).first() if book_exist: User_Book.query.filter_by(user_id=current_user.id, book_id=isbn).delete() db.session.commit() return jsonify({"success": True, "delete": True}) else: current_user.add_book(book, authors=authors, pages=pages, title=title) except KeyError: return redirect(url_for("errors.bad_request")) return jsonify({"success": True, "delete": False})
def account(): if current_user.role != 'admin': form = UpdateAccountForm() if form.validate_on_submit(): form.validate_name(form.name) form.validate_email(form.email) current_user.name = form.name.data current_user.email = form.email.data db.session.commit() flash('Reader account has been updated', 'success') else: form.name.data = current_user.name form.email.data = current_user.email # return render_template('account.html', title='Account', form=form) else: form = BookForm() if form.validate_on_submit(): books = Book.query.filter_by(title=form.title.data).all() for book in books: if book.author == form.author.data: flash('This book is already in the database', 'danger') else: book = Book() book.title = form.title.data book.author = form.author.data book.summary = form.summary.data db.session.add(book) db.session.commit() flash(f'Added book {book.title}', 'success') form.title.data = '' form.author.data = '' form.summary.data = '' return render_template('account.html', title='Account', form=form)
def create_book(): name = request.json['name'] tagline = request.json['tagline'] category_id = request.json['category_id'] author_id = request.json['author_id'] if 'short_desc' in request.json: short_desc = request.json['short_desc'] else: short_desc = "" new_book = Book(name, tagline, short_desc, category_id, author_id) db.session.add(new_book) db.session.commit() result = book_schema.dump(new_book) data = { 'message': 'New Book Created!', 'status': 201, 'data': result } return make_response(jsonify(data))
def edit(): form = EditForm() existing_data = [] for i in range(5): j = Book.query.filter_by(user_id=current_user.id).filter_by(rank=i + 1).first() existing_data.append(j) if form.validate_on_submit(): form_data = [(form.title1.data, form.author1.data), (form.title2.data, form.author2.data), (form.title3.data, form.author3.data), (form.title4.data, form.author4.data), (form.title5.data, form.author5.data)] for i in range(5): # b = Book.query.filter_by(user_id=current_user.id).filter_by(rank=i+1).first() b = existing_data[i] if b: b.title = form_data[i][0] b.author = form_data[i][1] db.session.commit() else: b = Book(user_id=current_user.id, rank=i + 1, title=form_data[i][0], author=form_data[i][1]) db.session.add(b) db.session.commit() return (redirect(url_for('index'))) return (render_template('edit.html', title='Edit', form=form, existing_data=existing_data))
def add(): form = AddBookForm() if form.validate_on_submit(): new_book = Book( isbn=form.isbn.data, title=form.title.data, origin_title=form.origin_title.data, # subtitle=form.subtitle.data, author=form.author.data, # translator=form.translator.data, publisher=form.publisher.data, image=form.image.data, # pubdate=form.pubdate.data, tags_string=form.tags.data, pages=form.pages.data, # price=form.price.data, # binding=form.binding.data, numbers=form.numbers.data, summary=form.summary.data or "") # catalog=form.catalog.data or "") db.session.add(new_book) db.session.commit() flash(u'O livro %s foi adicionado à biblioteca!' % new_book.title, 'success') return redirect(url_for('book.detail', book_id=new_book.id)) return render_template("book_edit.html", form=form, title=u"Adicionar novo livro")
def importBooks(): api1 = "https://www.googleapis.com/books/v1/volumes?q=" form = ImportBooks() global results if form.validate_on_submit() and form.submit.data: results = [] query = "+".join(form.keywords.data.split()) r = requests.get(api1 + query) jsonify = json.loads(r.content) #print(json.dumps(jsonify, indent=4, sort_keys=True)) for x in jsonify["items"]: results.append({"title": x["volumeInfo"]["title"]}) try: results[-1]["author"] = x["volumeInfo"]["authors"] except: results[-1]["author"] = "N/A" try: results[-1]["description"] = x["volumeInfo"]["description"] except: results[-1]["description"] = "N/A" try: results[-1]["genre"] = x["volumeInfo"]["categories"] except: results[-1]["genre"] = "N/A" print(results) if request.method == "POST" and form.move.data: print(results) for x in range(9): print(request.form.get(str(x))) data = request.form.getlist("checkbox") for x in data: flash(results[int(x)]["title"] + " - " + str(results[int(x)]["author"]) + " has been imported") author = Author.query.filter_by( name=results[int(x)]["author"][0]).first() if author is None: author = Author(name=results[int(x)]["author"][0]) db.session.add(author) db.session.commit() author_number = '' author = results[int(x)]["author"][0] authors = Author.query.all() print(author) for writer in authors: if author == writer.name: author_number = writer.id book = Book(title=results[int(x)]["title"], author_id=author_number, description=results[int(x)]["description"], genre=results[int(x)]["genre"][0]) db.session.add(book) db.session.commit() print("click") results = [] return render_template('import.html', title='Import Books', form=form, results=results)