Flask模板未呈现,并且不会插入数据库

时间:2019-09-25 12:12:56

标签: python-3.x flask sqlalchemy jinja2

我正在制作一个模板,该模板显示有关图书详细信息的描述。登录的用户只能撰写有关该书的评论,因此,如果用户未进行评论,则“ review.html”模板将向他显示有关该书的信息。这本书加上一个供他输入评论和评分的表格,如果已经提交了他的评论,它将以引导列表的形式向他显示该信息以及他的评论。当我提交评论时,没有任何反应,URL保持不变,但是我提交的信息被添加到其中,并添加了“ success.html”模板。

  

Application.py

@app.route("/books/<int:book_id>", methods=["GET", "POST"])
def review(book_id):
    ''' Prints to user Full information about a book + API information + prompts for user's review. '''

    # Get book information from books table using book_id got from books.html
    bookInfo = db.execute("SELECT * FROM books WHERE id=:book_id", {"book_id": book_id}).fetchone()

    # Error handling.
    if bookInfo is None:
        raise RuntimeError("Error @ route: review, didn't fetch book information from books table.")

    # Need ISBN from books template.
    res = requests.get("https://www.goodreads.com/book/review_counts.json", params={"key": "RXTP9fIaG5qVUetlVTHgQ", "isbns": f"{bookInfo['isbn']}"})

    if res is None:
        raise RuntimeError("Error @ route: reveiw, Error in goodReads API.")

    # Convert API response to JSON format.
    bookInfo2 = res.json()

    # GoodReads API values.
    averageRating = bookInfo2["books"][0]["average_rating"]
    ratingsCount = bookInfo2["books"][0]["ratings_count"]

    # Check if the user made a review
    haveReview = db.execute("SELECT * FROM reviews WHERE user_id=:user_id", {"user_id": session["user_id"]}).fetchone()

    if haveReview is None:

        if request.method == "POST":

            # User review and rating.
            review = request.form["review"]
            rating = int(request.form["rating"])

            if db.execute("INSERT INTO reviews (user_id, book_id, review_text, review_rating)\
                           values (:user_id, :book_id, :review_text, :review_rating)",\
                           {"user_id": 1, "book_id": book_id, "review_text": review,\
                           "review_rating": int(rating)}) is None:

                           raise RuntimeError("Error @ route review, didn't insert into reviews table.")
            else:
                db.commit()
                return render_template("success.html")

        return render_template("review.html",bookInfo=bookInfo,averageRating=averageRating,ratingsCount=ratingsCount,\
                               makeReview="0")



    return render_template("review.html",bookInfo=bookInfo,averageRating=averageRating,ratingsCount=ratingsCount, \
                          haveReview=haveReview,makeReview="1")

  

review.html

{%extends "base.html"%}

{%block title%}Review{%endblock%}
 <!-- {%block var2%}{{url_for('register')}}{%endblock%} -->


{%block body%}

<!-- Book details, and user's review -->
<div class="container">
<dl class="row">
<dt class="col-sm-3">Book title</dt>
<dd class="col-sm-9">{{bookInfo.title}}</dd>

<dt class="col-sm-3">Book author</dt>
<dd class="col-sm-9">{{bookInfo.author_name}}</dd>

<dt class="col-sm-3">ISBN</dt>
<dd class="col-sm-9">{{bookInfo.isbn}}</dd>

<dt class="col-sm-3">Publication year</dt>
<dd class="col-sm-9">{{bookInfo.publish_year}}</dd>

<dt class="col-sm-3">GoodReads average Rating</dt>
<dd class="col-sm-9">{{averageRating}}</dd>

<dt class="col-sm-3">Goodreads number of ratings</dt>
<dd class="col-sm-9">{{ratingsCount}}</dd>
</div>

{%if makeReview == '1'%}
<div class="container">
  <dl class='row'>
  <dt class="col-sm-3">Your rating</dt>
  <dd class="col-sm-9">{{haveReview.review_rating}} </dd>

 <dt class="col-sm-3">Your review</dt>
 <dd class="col-sm-9"> {{haveReview.review_text}}</dd>
</div>

{%elif makeReview == '0'%}
  <form class="container">
  <div class="form-group">
    <label for="review">Your Review</label>
    <textarea class="form-control" id="review" name="review" placeholder="Submit a review." rows="3"></textarea>
  </div>
  <div class="form-group">
    <label for="rating">Your rating</label>
    <input type="number" class="form-control" id="rating" name="rating" placeholder="Submit a rating.">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
  </form>
{%endif%}

{%endblock%}

1 个答案:

答案 0 :(得分:0)

我认为您应为帖子指定top_leaders(Lahman::Batting, R, 5) #Selecting by R # playerID R #1 hamilbi01 198 #2 brownto01 177 #3 ruthba01 177 #4 oneilti01 167 #5 gehrilo01 167

method="post"

因为default method for forms is GET.,否则 <form class="container" method="post"> 就不会request.method == "POST" ...