我从http请求访问响应数据时遇到问题。如果我将响应传递给html,然后从中获取想要的特定数据,但如果我尝试在python文件中获取响应的同一部分并将其传递给html,我就能得到它。它说“字典中没有book属性”。
我的html
{% extends "layout.html" %}
{% block heading %}
Search Page
{% endblock %}
{% block body %}
the result of the http request:
<p> {{res}} </p>
I want to add this info from the request
<p>{{res.books[0].average_rating}}
{{res.books[0].work_ratings_count}}</p>
to this dictionary
{{apiDict}}
but the when I use the same syntax to access the average rating and ratings count
from
'res' in my python file it says the respose has no book object, why does this
happen?
{% endblock %}
这是我的python /烧瓶代码:
@app.route("/api/<isbn>", methods=["GET"])
def apiacc(isbn):
res = requests.get("https://www.goodreads.com/book/review_counts.json", params=.
{"key": "lzhHXUd9kUpum244vufV2Q", "isbns": isbn}).json()
# avg = res.books[0].average_rating
# rc = res.books[0].work_ratings_count
book = db.execute("SELECT * FROM books WHERE isbn = :i", {"i": isbn}).fetchone()
db.commit()
apiDict = {
"title": book.title,
"author": book.author,
"year": book.year,
"isbn": isbn
}
# apiDict["average_score"] = res.books[0].average_rating
# apiDict["review_count"] = res.books[0].work_ratings_count
return render_template("api.html", res = res, apiDict=apiDict)
我想拥有这样的python代码:
apiDict = {
"title": book.title,
"author": book.author,
"year": book.year,
"isbn": isbn,
"average_score": avg,
"review_count": rc
}
并且仅将apiDict传递给api.hmtl作为唯一值,但是我得到了前面提到的错误。enter image description here
请求返回的res
将是字典。在模板中,Jinja支持使用点运算符获取dict值,例如:
{{ res.books }}
但是在Python中,必须使用方括号运算符来获取字典中的值(用于获取属性的点运算符:]
data = res['books']