Ejemplo n.º 1
0
def search():
    post_data = request.form.to_dict()
    search_terms = post_data.get('terms')

    reviews = get_reviews(search_terms, order_field='rating')

    rating = get_average_rating(search_terms)

    return render_template('movie.html',
                           movie=search_terms.title(),
                           avg_rating=rating,
                           reviews=reviews)
Ejemplo n.º 2
0
def bookdata(book_isbn):
    book = db.execute("select * from books where isbn = :isbn", {
        'isbn': book_isbn
    }).fetchone()
    if book == None:
        return "Book Not Found" + "    Error 404"

    greview = get_reviews(book_isbn)

    return jsonify(title=book['title'],
                   author=book['author'],
                   year=book['year'],
                   isbn=book_isbn,
                   review_count=greview.rating_count,
                   average_rating=greview.average_rating)
Ejemplo n.º 3
0
def book(isbn_num):
    # User reached route via POST
    if request.method == 'POST':

        # Use helper function `get_book()` to store results in book
        book = get_book(isbn_num)

        # Use Goodreads API https://www.goodreads.com/api
        goodreads_response = requests.get(
            "https://www.goodreads.com/book/review_counts.json",
            params={
                "key": goodreads_key,
                "isbns": isbn_num
            })
        goodreads_json = (goodreads_response.json()['books'][0])

        # Use helper function `get_reviews()` to store review results of that book
        reviews = get_reviews(isbn_num)

        # Get corresponding fields from 'search form'
        numRating = request.form.get('reviewStar')
        textRating = request.form.get('reviewText')
        if (numRating is not None or textRating is not None):
            # If user has not submitted a number rating, assign 5 as default
            if numRating is '':
                numRating = 5
                numRating = int(numRating)
            else:
                numRating = int(numRating)

            # Verify that user has logged in
            if (session['user_id'] is None):
                print("You have to log in to submit a review")
                return redirect(url_for('login'))
            else:
                user_id = session['user_id']

            # Check user_id from the database to ensure that user has not submitted another review for that book
            hasCommented = userHasCommented(user_id, isbn_num)
            if (hasCommented is True):
                flash("You have already submitted a comment for that book!")
                return redirect(url_for('search'))
            else:
                # Insert into database
                comment = db.execute(
                    'INSERT INTO reviews (isbn, user_id, rating, text_review) VALUES (:isbn, :user_id, :rating, :text_review)',
                    {
                        "isbn": isbn_num,
                        "user_id": user_id,
                        "rating": numRating,
                        "text_review": textRating
                    })
                db.commit()
                db.close()
                # Give feedback to user
                flash("Submitted your comment!")
        return render_template('book.html',
                               isbn_num=isbn_num,
                               book=book,
                               book_json=goodreads_json,
                               reviews=reviews)
    else:
        flash("GET Method Not Allowed!")
        return redirect(url_for('search'))
Ejemplo n.º 4
0
def bookdetails(book_isbn):
    revs = list()

    # when the user is leaving a review about that specific book
    if request.method == 'POST':
        row = db.execute("select id from books where isbn = :isbn ", {
            'isbn': book_isbn
        }).fetchone()
        book_id = row[0]
        rating = request.form['rate']
        review = request.form['review']

        # if the user entered an empty input he will be directed to the error page
        if rating == None or not review.strip():
            return render_template(
                'error.html',
                error="you must provide both rate and review !",
                direction="/bookpage")

        # after validating the user input, it will be stored into the database and displayed
        else:
            try:
                db.execute(
                    'insert into reviews(bookid,userid,review,rating) VALUES(:book_id,:user_id,:review,:rating)',
                    {
                        'book_id': book_id,
                        'user_id': session['user_id'],
                        'review': review,
                        'rating': rating
                    })
                db.commit()
                return redirect(request.referrer)
            # expecting that the user would make a review more than once about the same book
            except:
                return render_template(
                    "error.html",
                    error="you already made a review on this book",
                    direction="/bookpage")

    # when the user is just requesting for the bookdetails page , the book info and it`s reviews will be displayed for him
    else:
        try:
            book = db.execute("select * from books where isbn = :isbn", {
                'isbn': book_isbn
            }).fetchone()
        except:
            return render_template("error.html",
                                   error="error fetching data",
                                   direction="/bookpage")
        oneBook = Books(int(book['id']), book['author'], book['title'],
                        book_isbn, book['year'])

        # getting any review about that book
        try:
            reviews = db.execute(
                'Select rating, review, userid from reviews where bookid = :bookid',
                {
                    'bookid': book.id
                }).fetchall()
        except:
            return render_template("error.html",
                                   error="error fetching data",
                                   direction="/bookpage")

        # parsing data to a list of UserReview instance
        for i in range(len(reviews)):
            # parsing the users who made the reviews
            user = db.execute('select username from users where id = :userid',
                              {
                                  'userid': reviews[i]['userid']
                              }).fetchone()
            oneReview = UserReview(reviews[i]['review'], user['username'],
                                   reviews[i]['rating'])
            revs.append(oneReview)

        ## calling the function to get the data from goodreads api
        greview = get_reviews(book_isbn)
        return render_template("bookdetails.html",
                               book=book,
                               greview=greview,
                               reviews=revs)
Ejemplo n.º 5
0
def books(isbn):
    """ Displays all information about book """

    book = list(
        db.execute("SELECT * FROM books WHERE isbn = :isbn", {"isbn": isbn}))

    if len(book) < 1:
        error = "Cannot find details on this book"
        return render_template("apology.html", error=error)

    res = {
        "isbn": book[0][0],
        "title": book[0][1],
        "author": book[0][2],
        "year": book[0][3]
    }
    gr = requests.get("https://www.goodreads.com/book/review_counts.json",
                      params={
                          "key": KEY,
                          "isbns": isbn
                      })
    g = gr.json()
    # if gr is None TODO

    if request.method == "POST":
        if session["user_id"] is None:
            error = "You must be logged in to leave a review"
            return render_template("apology.html", error=error)

        res = list(
            db.execute("SELECT * FROM reviews WHERE user_id = :user_id",
                       {"user_id": session["user_id"]}))
        if len(res) > 1:
            error = "Users may only leave one review per book"
            return render_template("apology.html", error=error)

        score = int(request.form.get("score"))
        review = request.form.get("review")

        # Submit review
        db.execute(
            "INSERT INTO reviews (score, isbn, user_id, review) VALUES (:score, :isbn, :user_id, :review)",
            {
                "score": score,
                "isbn": isbn,
                "user_id": session["user_id"],
                "review": review
            })
        db.commit()

        # Gather reviews to display on page
        reviews = get_reviews(db, isbn)

        return render_template("books.html",
                               res=res,
                               reviews=reviews,
                               gr=g["books"])

    else:
        reviews = get_reviews(db, isbn)
        return render_template("books.html",
                               res=res,
                               reviews=reviews,
                               gr=g["books"])
Ejemplo n.º 6
0
def index():
    reviews = get_reviews()

    return render_template('index.html', reviews=reviews)