我正在尝试使用 Flask-SQLAlchemy 从 SQLite 文档中获取特定行,然后将其通过管道传输到 JSON 中,以便将其推送到页面。我是 Flask 和 Python 的新手,但我有足够的知识来做我需要做的事情,我只是不知道如何做。
我目前的代码:
@app.route('/posts/<pid>', methods=["GET", "POST"])
def posts(pid):
if request.method == "POST":
post = Posts.query.filter_by(id=pid).first()
comment = request.form.get('comment')
# poid = request.form.get('postid')
poid = pid
print(poid)
c = Comments(id=len(Comments.query.all())+1, comment=comment, user=current_user.username, postid=poid)
db.session.add(c)
db.session.commit()
return render_template("post.html", title=post.title, body=post.body, user=post.user, id=poid)
post = Posts.query.filter_by(id=pid).first()
# c = Comments()
# print(json.dumps(c, cls=AlchemyEncoder))
comments = Comments.query.filter_by(id=pid).all()
jsonToPush = {'comments': []}
print(comments)
for comment in comments:
print(comment.postid)
if comment.postid == pid:
print("Found comment")
jsonToPush['comments'].append({ "id": comment.id, "postid": comment.postid, "comment": comment.comment, "user": comment.user})
print(jsonToPush)
return render_template("post.html", title=post.title, body=post.body, user=post.user, id=pid, jtp=jsonToPush)
return render_template("post.html", title=post.title, body=post.body, user=post.user, id=pid)
当我print(comments)打印出来[<Comments 1>]
当我print(comment.postid)打印出来1
无论有多少评论,它都只打印出来1。
我已经制定了如何在站点中使用 JSON 的计划,我只需要帮助将 SQL 带到站点。任何帮助表示赞赏。谢谢!
呼啦一阵风
相关分类