我是flask的新手,并尝试构建一个api,该api返回数据库中所有帖子的json响应,但是我只能返回一个帖子,而无法获取所有信息。(我使用的是香草烧瓶,不使用任何包就像“烧瓶躁动”)。这是我尝试过的。
from .db import get_db
from flask import jsonify,Blueprint
bp= Blueprint("api",__name__,url_prefix="/api")
@bp.route("/posts",methods=("GET",))
def get_posts():
db = get_db()
posts=db.execute('SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' ORDER BY created DESC').fetchall()
for post in posts:
title=post["title"]
body=post["body"]
author=post["username"]
return jsonify(
title=title,
body=body,
author=author
)'''
它仅以JSON格式返回第一篇文章。我想要所有帖子。
之所以发生,是因为您要在for循环内返回结果,因此,它停止迭代并返回第一个结果。您可以创建一个列表并将jsonify附加到该列表,或者可以使用棉花糖为您进行序列化。如果要创建列表并追加结果,可以执行以下操作:
post_list = []
for post in posts:
...
post_list.append(jsonify(
title=title,
body=body,
author=author
))
return post_list
问题是jsonify返回Flask Response
,因此尝试将其追加到列表不是一个好主意。像这样,如何从HTTP请求中返回几个Responses?
更好的主意是将您所有的帖子存储在列表中,然后然后
对它们进行JSON修饰。post_list = []
for post in posts:
title=post["title"]
body=post["body"]
author=post["username"]
resp = {"title":title, "body":body, "author":author}
post_list.append(resp)
return jsonify(post_list)