Beispiel #1
0
def add_book(form):
    title = form.get('title')
    author = form.get('author')
    isbn = form.get('isbn')
    book = Books(title=title, author=author, isbn=isbn)
    year = form.get('year')
    if year:
        year = int(year)
        book.year = year
    review = form.get('review')
    rating = form.get('rating')

    try:
        db.session.add(book)
        db.session.commit()
    except Exception as e:
        print(e)
        return False
    book = Books.query.filter_by(title=title).first()
    print('Book', book)
    if rating:
        rating = int(form.get('rating'))
        book.num_rating = 1
        book.avg_rating = rating
        review = Reviews(rating=rating, text=review, bookid=book.id)
    try:
        db.session.add(book)
        db.session.add(review)
        db.session.commit()
    except:
        return False
    return True
def likedUsrBook(request, id):
	uId = request.user.id
	book = get_object_or_404(Books, id=id)
	new_book = Books(id=None, title = book.title, author= book.author, 
		date_added = book.date_added, image=book.image,user_id = uId)
	new_book.save()
	return HttpResponseRedirect(reverse('books:results'))
Beispiel #3
0
 def delete(self, id):
     if not self._auth.is_authorized():
         abort(401)
     books = Books.query.filter_by(id=id).first()
     if books.user_id != self._auth.get_user().id:
         abort(403)
     Books.delete(books)
     return jsonify({"deleted": True})
Beispiel #4
0
 def Book_delete(id: int):
     if not auth.is_authorized():
         return redirect('/login')
     book = Books.query.filter_by(id=id).first()
     if book.user.id != auth.get_user().id:
         abort(403)
     Books.delete(book)
     return redirect('/books')
Beispiel #5
0
    def setUp(self):
        Base.metadata.drop_all(self.engine)
        Base.metadata.create_all(self.engine)

        self.author_1 = Authors(
            name='Nason Alex',
            born='1943-03-26',
            nationality='American',
            education='Yale University, BA, 1965',
            description='investigative journalist',
            wikipedia_url='https://en.wikipedia.org/wiki/Bob_Woodward',
            image_url=
            'http://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Bob_Woodward.jpg/220px-Bob_Woodward.jpg'
        )
        self.author_2 = Authors(
            name='Patrick Rothfuss',
            born='1994-08-13',
            nationality='Chinese',
            image_url=
            "http://upload.wikimedia.org/wikipedia/commons/thumb/7/7f/Patrick-rothfuss-2014-kyle-cassidy.jpg/250px-Patrick-rothfuss-2014-kyle-cassidy.jpg"
        )
        self.author_3 = Authors(name='Robin Hortz',
                                nationality='Australian',
                                born='1952-03-05')
        self.publisher_1 = Publishers(
            name='Simon & Schuster',
            founded='1924',
            wikipedia_url="https://en.wikipedia.org/wiki/Simon_%26_Schuster",
            website="http://www.simonandschuster.com")
        self.publisher_2 = Publishers(name='HarperCollins',
                                      founded='1989',
                                      location='New York',
                                      website='http://harpercollins.com')
        self.publisher_3 = Publishers(name='Penguin Group',
                                      founded='1935',
                                      location='City of Westminster, London')

        self.book_1 = Books(title='Royal Assassin',
                            google_id='kx12345',
                            publication_date='2003-04-05')
        self.book_1.authors.append(self.author_3)

        self.book_2 = Books(title='Under the sea',
                            google_id='34567',
                            publication_date='2017-09-21')
        self.book_2.publishers.append(self.publisher_1)

        self.author_2.publishers.append(self.publisher_2)

        self.session.add(self.author_1)
        self.session.add(self.author_2)
        self.session.add(self.author_3)
        self.session.add(self.publisher_1)
        self.session.add(self.publisher_2)
        self.session.add(self.publisher_3)
        self.session.add(self.book_1)
        self.session.add(self.book_2)
        self.session.commit()
Beispiel #6
0
def del_book(id):
    exists = Books.select().filter(id=id).exists()

    if not exists:
        return jsonify(
            {"message": "Can't find book with id - `{id}`".format(id=id)}), 404

    Books.delete().where(Books.id == id).execute()
    return jsonify({}), 204
Beispiel #7
0
    def create_book(valid):
        if valid:
            #todo ----
            if request.method == 'GET':
                books = Books.query.all()

                if not books:
                    abort(make_response(jsonify('No books added yet')))

                return jsonify({
                    'success': True,
                    'books': [Books.details(book) for book in books]
                })

            else:
                try:
                    new_book = request.get_json()
                except Exception as e:
                    abort(
                        make_response(
                            jsonify({'error message': 'Incorrect data'})))

                if all(k in new_book for k in ('title', 'author', 'user_id')):
                    book = Books(title=new_book['title'],
                                 author=new_book['author'],
                                 created_by=new_book['user_id'])
                    try:
                        book.insert()
                    except sqlalchemy.exc.IntegrityError as e:
                        abort(
                            make_response(
                                jsonify({
                                    'message':
                                    'provided user does not exist'
                                })))
                    except Exception as e:
                        db.session.rollback()
                        abort(404, e)

                    result = {
                        "success":
                        True,
                        "message":
                        'book ' + new_book['title'] +
                        ' has been added successfully'
                    }
                    return jsonify(result)
                else:
                    abort(
                        make_response(
                            jsonify({
                                'message':
                                'You seem to have missed some data: Provide title of the book, its author '
                                'and user_id who created the book'
                            })))
Beispiel #8
0
def books():
    if request.method == "GET":
        all_books = Books.query.all()
        return make_response({"book": BooksSchema(many=True).dump(all_books)},
                             200)

    book = Books.query.filter_by(isbn=request.json['isbn']).first()
    if book:
        book.isbn = request.json['isbn']
        book.publisher = request.json['publisher']
        book.author = request.json['author']
        book.publication_year = request.json['publication_year']
        book.category = request.json['category']
        book.count = request.json['count']
        book.title = request.json['title']
        db.session.commit()
        return make_response({"Book": BooksSchema().dump(book)}, 200)
    else:
        book = Books()
        book.isbn = request.json['isbn']
        book.title = request.json['title']
        book.publisher = request.json['publisher']
        book.author = request.json['author']
        book.publication_year = request.json['publication_year']
        book.category = request.json['category']
        book.count = request.json['count']

        db.session.add(book)
        db.session.commit()
        return make_response({"Book": BooksSchema().dump(book)}, 200)
Beispiel #9
0
    def post_books(payload):
        body = request.get_json()
        try:

            book = Books(body['book_name'], body['book_type'],
                         body['book_rate'])
            book.insert()

        except BaseException:
            abort(401)

        return jsonify({"sucess": True, "book": book.id}), 200
Beispiel #10
0
def addbook(request):
    books = Books.objects.all()
    if request.user.is_staff:
        if request.method == "POST":
            name = request.POST['book']
            author = request.POST['author']
            copies = request.POST['copies']
            status = request.POST['status']
            book = Books(name=name, author=author, copies=copies, status=status)
            book.save()
            return redirect("/lend/addbook")
        else:
            return render(request, "lend/addbook.html", {'books': books})
Beispiel #11
0
def endpoint(id=None):
    if request.method == 'GET':
        if id:
            return jsonify(model_to_dict(Books.get(Books.id == id)))
        else:
            bookList = []
            for book in Books.select():
                bookList.append(model_to_dict(book))
            return jsonify(bookList)

    if request.method == 'POST':
        new_book = dict_to_model(Books, request.get_json())
        new_book.save()
        return jsonify({"success": True})
Beispiel #12
0
def update(id):
    book = Books.query.filter_by(id=id).first()
    if request.method == 'POST':
        if book:
            db.session.delete(book)
            db.session.commit()

            title = request.form['title']
            author = request.form['author']
            genre = request.form['genre']
            heigh = request.form['heigh']
            publisher = request.form['publisher']

            book = Books(id=id,
                         title=title,
                         author=author,
                         genre=genre,
                         heigh=heigh,
                         publisher=publisher)
            db.session.add(book)
            db.session.commit()
            return redirect(f'/view/{id}')
        else:
            return "Book with id = {0} Does not exits".format(id)
    return render_template('update.html', data=book, title="Update")
Beispiel #13
0
def get_book(id):
    try:
        book = Books.get(id=id)
        return jsonify(bookSchema.dump(book).data), 200
    except Books.DoesNotExist:
        return jsonify(
            {"message": "Can't find book with id - `{id}`".format(id=id)}), 404
Beispiel #14
0
def regist():

    name = request.forms.decode().get('name')
    volume = request.forms.decode().get('volume')
    author = request.forms.decode().get('author')
    publisher = request.forms.decode().get('publisher')
    memo = request.forms.decode().get('memo')
    registId = request.forms.decode().get('id')

    if request.forms.get('next') == 'back':
        response.status = 307
        response.set_header("Location", '/add')
        return response
    else:
        if registId is not None:
            books = session.query(Books).filter(Books.id_ == registId).first()
            books.name = name
            books.volume = volume
            books.author = author
            books.publisher = publisher
            books.memo = memo
            session.commit()
            session.close()
        else:
            logging.info('Adding a new book')
            books = Books(name=name,
                          volume=volume,
                          author=author,
                          publisher=publisher,
                          memo=memo)
            session.add(books)
            session.commit()
            session.close()
        redirect('/list')
def search_book():
    title = request.args.get('title', default=None, type=str)

    books = Books.objects(book_title__icontains=title).only(
        'book_title', 'id', 'cover_image', 'avg_rating', 'genres', 'author')

    lim = 10
    total = books.count()
    if total % lim != 0:
        total = int(total / lim) + 1
    else:
        total = int(total / lim)

    if 'user' in session:
        user = Users.objects(username=session['user']).get()
        shelves = []
        for shelf in user['shelves']:
            shelves.append(shelf['shelf_title'])

        return jsonify({
            "books": books.to_json(),
            "total": total,
            "shelves": shelves
        })

    return jsonify({"books": books.to_json(), "total": total})
Beispiel #16
0
 def post(self):
     if not self._auth.is_authorized():
         abort(401)
     args = books_parser.parse_args()
     books = Books.add(args['title'], args['author'], args['content'],
                       args['link'], self._auth.get_user())
     return jsonify(books.serialize)
def get_book_recommendation():
    user = Users.objects(username=session['user']).get()

    genres = []
    ignore_books = []
    for shelf in user.shelves:
        for book in shelf.shelved_books:
            ignore_books.append(book['id'])
            for genre in book.genres:
                genres.append(genre)

    genres = list(dict(Counter(genres).most_common()).keys())

    if len(genres) > 5:
        genres = genres[:5]

    books = Books.objects(
        Q(avg_rating__gte=4.5) & Q(genres__in=list(genres))
        & Q(id__nin=list(set(ignore_books)))).only('book_title', 'id',
                                                   'cover_image', 'author',
                                                   'genres',
                                                   'avg_rating').to_json()

    books = json.loads(books)
    books = random.sample(books, 6)

    return jsonify({"rec": json.dumps(books)})
Beispiel #18
0
def addbook(request):
    books = Books.objects.all()
    if request.user.is_staff:
        if request.method == "POST":
            name = request.POST['book']
            author = request.POST['author']
            copies = request.POST['copies']
            status = request.POST['status']
            book = Books(name=name,
                         author=author,
                         copies=copies,
                         status=status)
            book.save()
            return redirect("/lend/addbook")
        else:
            return render(request, "lend/addbook.html", {'books': books})
Beispiel #19
0
def main():
    f = open("/Users/prakashtiwari/Desktop/project1/books.csv")
    reader = csv.reader(f)
    for isbn, title, author, year in reader:
        books = Books (isbn = isbn, title = title, author = author, year = year)
        db.session.add(books)
        print(f"Added books isbn = {isbn} title =  {title} author = {author} year = {year}.")
    db.session.commit()
def remove_review():
    book = request.get_json()['book']

    book = Books.objects(id=book).get()
    book.reviews.remove(book.reviews.get(username=session['user']))
    book.save()

    return jsonify({'result': True})
Beispiel #21
0
 def create(self, data):
     title = data['title']
     author = data['author']
     unit_price = data['unit_price']
     books = Books(title, author, unit_price)
     db.session.add(books)
     db.session.commit()
     return create_books(books)
Beispiel #22
0
def insert_into_table(file_name):
    with open(file_name) as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        next(reader, None)
        for isbn, title, author, year in reader:
            item = Books(isbn, title, author, year)
            db.session.add(item)
            db.session.commit()
Beispiel #23
0
def book_add(msg = ""):
	book_form = BookForm(request.form)
	user = auth.get_logged_in_user()
	if request.method == "POST":
		books = Books(
			ownership = user,
			title = book_form.title.data,
			author = book_form.author.data,
			isbn = book_form.isbn.data,
		)
		books.save()
		flash("Book successfully saved")
		msg = "Book successfully saved"
		book_form = BookForm()
		return render_template("book_add.html", book_form=book_form, msg=msg)
	else:
		return render_template("book_add.html", book_form=book_form, msg=msg)		
Beispiel #24
0
def dashboard(msg=None):
	user = auth.get_logged_in_user()
	try:
		books = Books.select().where(
			Books.ownership == user).order_by(Books.id.desc())
		return object_list("book_list.html", books, 'book_list')
	except Books.DoesNotExist:
		return render_template("dashboard.html", msg=msg)
	return render_template("dashboard.html", msg=msg)
Beispiel #25
0
 def dark_Books_create_form():
     if not auth.is_authorized():
         return redirect('/login')
     form = BooksCreateForm()
     if form.validate_on_submit():
         title = form.title.data
         author = form.author.data
         content = form.content.data
         link = form.link.data
         Books.add(title=title,
                   author=author,
                   content=content,
                   link=link,
                   user=auth.get_user())
         return redirect('/')
     return render_template('dark_books-create.html',
                            title='Создать книгу',
                            form=form)
def main():
    print 'Opening books.json'
    path = os.path.join(os.path.split(__file__)[0], 'books.json')
    json_data = open(path, 'r').read()
    books = json.loads(json_data)['books']

    print 'Loading books into database...'
    map(lambda book: Books.post_book(book), books)
    
    print 'Done loading.'
def add_book_to_shelf():
    shelf = request.get_json()['shelf']
    book = request.get_json()['book']

    user = Users.objects(username=session['user']).get()

    user.shelves.get(shelf_title=shelf).shelved_books.append(
        Books.objects(id=book).get())
    user.save()
    return jsonify({"result": True})
def remove_shelf_book():
    book = request.get_json()['book']
    shelf = request.get_json()['shelf']

    user = Users.objects(username=session['user']).get()
    user.shelves.get(shelf_title=shelf).shelved_books.remove(
        Books.objects(id=book).get())

    user.save()

    return jsonify({'result': True})
Beispiel #29
0
def delete_book(current_user, book_id):
    try:
        book = Books().get_by_id(book_id)
        if not book or book["user_id"] != current_user["_id"]:
            return {
                "message": "Book not found for user",
                "data": None,
                "error": "Not found"
            }, 404
        Books().delete(book_id)
        return jsonify({
            "message": "successfully deleted a book",
            "data": None
        }), 204
    except Exception as e:
        return jsonify({
            "message": "failed to delete a book",
            "error": str(e),
            "data": None
        }), 400
Beispiel #30
0
def populate(dbname, jsondata):
    """docstring for populate"""
    session = connect(dbname)

    with open(jsondata) as f:
        data = json.load(f)

    for i in data['books']:
        book_data = Books(Title = i["Title"], Author = i["Author"], ReadOrNot = "0")
        session.add(book_data)
    session.commit()
Beispiel #31
0
def add():
    binfo = bookinfo()
    for b in binfo:
        title, cover, author, category = b
        book = Books(title=title,
                     cover=cover,
                     author=author,
                     category=category)
        db.session.add(book)
        db.session.commit()
    return render_template("add.html")
Beispiel #32
0
    def new_books(payload, id):
        try:
            data = request.get_json()
            add_name = data.get('name')
            add_author = data.get('author')
            add_category = data.get('category_id')
            new_addition = Books(name=add_name,
                                 author=add_author,
                                 category_id=add_category)
            new_addition.insert()

            return jsonify({
                "name": add_name,
                "author": add_author,
                "category": add_category,
                "success": True,
                "message": "successfully added a new book"
            }), 200
        except Exception:
            abort(422)
Beispiel #33
0
def ship():
	user = auth.get_logged_in_user()
	#book = get_object_or_404(Books, Books.user == user, Books.id)
	if request.method == "POST":
		book_id = request.form["book_id"]
		b = Books.delete().where(Books.ownership == user and Books.id == book_id)
		b.execute()
		return render_template("shipped.html")
	else:
		print "wtf"
		return redirect(url_for("dashboard"))
Beispiel #34
0
 def test_books_insert(self):
     self.session.add(
         Books(title='Nothing to Envy',
               google_id='0385523912',
               publication_date='2009-12-29'))
     self.session.commit()
     result = self.session.query(Books).filter_by(
         title='Nothing to Envy').one()
     self.assertEqual(str(result.google_id), '0385523912')
     self.assertEqual(str(result.publication_date), '2009-12-29')
     self.session.query(Books).filter_by(title='Nothing to Envy').delete()
     self.session.commit()
Beispiel #35
0
def get_books(current_user):
    try:
        books = Books().get_by_user_id(current_user["_id"])
        return jsonify({
            "message": "successfully retrieved all books",
            "data": books
        })
    except Exception as e:
        return jsonify({
            "message": "failed to retrieve all books",
            "error": str(e),
            "data": None
        }), 500
Beispiel #36
0
def run(project_name, data_dir, product_dir, epubcheck_path, zip_path, pandoc_path):
	# check depend java
	try:
		output = subprocess.check_output(
			'java -version',
			stderr=subprocess.STDOUT,
			shell=True
		)
	except subprocess.CalledProcessError as e:
		# print(e.returncode)
		output = e.output
		print('Project Depends on Java(TM) SE Runtime Environment, Please Install Java first!')
		r = input('Already installed Java?(y/n)')
		if not 'yes'.startswith(r):
			return '\n Bye!'

	# check configuration
	epub_cfg = EpubGeneratorServiceConfig(
		project_name, 
		data_dir, 
		product_dir, 
		epubcheck_path, 
		zip_path, 
		pandoc_path)
	
	if not epub_cfg.validate_configuration():
		return epub_cfg.get_validation()
	
	if epub_cfg.confirm_configuration():
		cfg = epub_cfg.get_configuration()
		books = Books.create_from_file(cfg['data_books_file'])

		return epub_maker_run(**{
			'epubcheck_path': cfg['epubcheck_path'],
			'zip_path': cfg['zip_path'],
			'pandoc_path': cfg['pandoc_path'],
			'data_dir': cfg['data_dir'],
			'image_dir': cfg['image_dir'],
			'data_books': books,
			'product_dir': cfg['product_dir'],
			'product_book_dir': cfg['product_book_dir'],
			'product_epub_dir': cfg['product_epub_dir'],
			'product_failure_report_file': cfg['product_failure_report_file'],
			'product_success_report_file': cfg['product_success_report_file'],
			'data_json_filename': cfg['data_json_filename'],
			'data_meta_filename': cfg['data_meta_filename'],
			'chapteralone': cfg['chapteralone'],
			'with_indent': cfg['with_indent']
		})
	else:
		return '\nOk, may be you should change your configuation first, Bye!'
Beispiel #37
0
def search():
    books_data = [book.book_title for book in Books.query.all()]
    authors_data = [author.author_name for author in Authors.query.all()]
    data = sifter(books_data + authors_data)
    search_result = []
    if request.method == 'POST':
        form = SearchForm(request.form)
        if form.validate():

            search_result = Books.query.filter(
                Books.author.any(
                    Authors.author_name.like('%' + form.search.data + '%')
                )
            ).all()

            search_result += Books.query.filter(
                Books.book_title.like('%' + form.search.data + '%')
            ).all()
            search_result = sifter(search_result)
            search_result = [result.columns_data() for result in search_result]
            search_result.insert(0, Books.columns_names())

    return render_template('search.html', data=data, search_result=search_result)
Beispiel #38
0
def main(request):
    """Main listing."""
    #return HttpResponse("Hello world")
    books = list(Books.scan())
    return render_to_response("list.html", dict(books=books, user=request.user))