猿问

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

我正在尝试使用 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 带到站点。任何帮助表示赞赏。谢谢!


长风秋雁
浏览 415回答 2
2回答

呼啦一阵风

我修好了它。我现在的代码是这样的:@app.route('/posts/<postid>', methods=["GET", "POST"])@login_requireddef posts(postid):&nbsp; &nbsp; post = Posts.query.filter_by(id=postid).first()&nbsp; &nbsp; if request.method == "POST":&nbsp; &nbsp; &nbsp; &nbsp; comment = request.form.get('comment')&nbsp; &nbsp; &nbsp; &nbsp; c = Comments(id=len(Comments.query.all())+1, comment=comment, user=current_user.username, postid=postid)&nbsp; &nbsp; &nbsp; &nbsp; db.session.add(c)&nbsp; &nbsp; &nbsp; &nbsp; db.session.commit()&nbsp; &nbsp; &nbsp; &nbsp; return redirect('/posts/{}'.format(postid))&nbsp; &nbsp; # c = Comments()&nbsp; &nbsp; # print(json.dumps(c, cls=AlchemyEncoder))&nbsp; &nbsp; comments = Comments.query.filter_by(postid=postid).all()&nbsp; &nbsp; print(Comments.query.all())&nbsp; &nbsp; 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 答案得出了这个答案。给他荣誉,而不是我:)
随时随地看视频慕课网APP

相关分类

Python
我要回答