为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以从具有特定值的 SQLite 数据库中获取特定行,将其转换为 JSON

是否可以从具有特定值的 SQLite 数据库中获取特定行,将其转换为 JSON

长风秋雁 2021-08-05 10:22:44
我正在尝试使用 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 带到站点。任何帮助表示赞赏。谢谢!
查看完整描述

2 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

我修好了它。


我现在的代码是这样的:


@app.route('/posts/<postid>', methods=["GET", "POST"])

@login_required

def posts(postid):

    post = Posts.query.filter_by(id=postid).first()

    if request.method == "POST":

        comment = request.form.get('comment')

        c = Comments(id=len(Comments.query.all())+1, comment=comment, user=current_user.username, postid=postid)

        db.session.add(c)

        db.session.commit()

        return redirect('/posts/{}'.format(postid))

    # c = Comments()

    # print(json.dumps(c, cls=AlchemyEncoder))


    comments = Comments.query.filter_by(postid=postid).all()

    print(Comments.query.all())

    return render_template("post.html", title=post.title, body=post.body, user=post.user, id=postid, comments = [comment_dict(comment) for comment in comments])

编辑:我根据下面的 Attack68 答案得出了这个答案。给他荣誉,而不是我:)


查看完整回答
反对 回复 2021-08-05
  • 2 回答
  • 0 关注
  • 414 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号