首页 > 解决方案 > Flask 使用 id 来个性化登陆页面

问题描述

我正在完成烧瓶教程。我正在尝试修改教程代码以更好地理解它。下面是主页的代码。它访问人们在博客上写的所有帖子。

@bp.route('/')
def index():
    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()
    return render_template('blog/index.html', posts=posts)

我试图调整它,使它只显示该用户写的帖子。作为一个起点,我尝试将 id 作为输入变量传递给 index() 函数,就像函数 get_post() 所做的一样(见下文)

@bp.route('/create', methods=('GET', 'POST'))
@login_required

...

def get_post(id, check_author=True):
    post = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,)
    ).fetchone()

    if post is None:
        abort(404, "Post id {0} doesn't exist.".format(id))

    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post

但是,这会引发一个错误,其中 id 未被识别为输入变量。当我添加@login_required 时会发生这种情况,并且当我尝试将 ip 地址更改为“/int:id//”时,该地址在另一个以 id 作为输入的函数中使用。

谢谢您的帮助:))

标签: pythonflask

解决方案


推荐阅读