我正在尝试运行Flask应用程序,显示书概述页面并能够提交用户的评论。但是我遇到了两个问题:
1)当我尝试运行以下代码时,“ / books / 553803700”的网址将我重定向回首页。
我想
有问题review = db.execute("SELECT review FROM reviews WHERE review_by = :review_by", {"review_by": current_user}).fetchone()
2)如果我在上面注释该字符串,则页面有效。但是,当我尝试提交评论时,它显示为“未找到。在服务器上找不到所请求的URL。如果您手动输入URL,请检查拼写,然后重试。”
application.py文件:
from flask import Flask, session, render_template, request, redirect, flash, jsonify
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
....
### some app configuration, other routes
...
@app.route("/books/<isbn>")
def book(isbn):
try:
if globals()["session"]["username"]:
current_user = globals()["session"]["username"]
book = db.execute("SELECT * FROM books WHERE isbn = :isbn", {"isbn": isbn}).fetchone()
### here is that string
review = db.execute("SELECT review FROM reviews WHERE review_by = :review_by",
{"review_by": current_user}).fetchone()
if review is True:
return render_template("book.html", book=book, review=review)
else:
return render_template("book.html", book=book)
except:
return redirect("/login")
@app.route("/books/<isbn>/review", methods=['POST'])
def review(isbn):
review = request.form.get("review")
current_user = globals()["session"]["username"]
db.execute("INSERT INTO reviews (isbn, review_by, review) VALUES (:isbn, :review_by, :review)",
{"isbn": isbn, "review_by": current_user, "review": review})
db.commit()
db.close()
return redirect("/book/" + isbn)
book.html文件:
{% extends "layout.html" %}
{% block getin %}
<h1>{{ book.title }}</h1>
<ul>
<li>Title: {{ book.title }}</li>
<li>ISBN: {{ book.isbn }}</li>
<li>Author: {{ book.author }}</li>
<li>Year: {{ book.year }}</li>
</ul>
{% endblock %}
{% block user_info %}
<h2>Would you like to leave your review?</h2>
{% if review %}
<div class="user-review">
{{ review }}
</div>
{% else %}
<form name="submit-review" action="/book/{{book.isbn}}/review" method="POST">
<textarea type="text" name="review" class="form-control" placeholder="Leave your review here">
</textarea>
<button class="btn btn-primary">Submit</button>
</form>
{% endif %}
<div class="row" style="margin-top:50px">
GoodReads reviews:
</div>
{% endblock %}
非常感谢您为解决这两个问题所提供的帮助
答案 0 :(得分:0)
要解决第二个错误:
未找到。在服务器上找不到请求的URL。如果你 手动输入网址,请检查您的拼写,然后重试。
您需要添加反斜杠/
来路由@app.route("/books/<isbn>)
。它将类似于:
@app.route("/books/<isbn>/")
def book(isbn):
#...
答案 1 :(得分:0)
看看你的行动的价值。
...
<form name="submit-review" action="/book/{{book.isbn}}/review" method="POST">
...
让它替换为此:
...
<form name="submit-review" action="{{ url_for('book', isbn=book.isbn) }}" method="POST">
...
否则,尝试将其删除。
...
<form name="submit-review" action="" method="POST">
...