如何使用Flask / Jinja2查看会话变量?

时间:2017-04-04 15:01:24

标签: python session flask sqlalchemy

有人能告诉我如何在flask中查看会话变量,以便我可以检索当前登录的用户吗?使用我的'for loop',我可以查看迭代的所有项目,但我需要当前登录的用户...

提前致谢

app.py

engine = create_engine('sqlite:///dude.db', echo=True)
app = Flask(__name__)
@app.route('/')
def home():
    if session.get('logged_in'):
        Session = sessionmaker(bind=engine)
        s = Session()
        user = s.query(User.username)
        for i in user:
            print i
        return render_template('index.html', user = user)
    else:
        return render_template('index.html')

1 个答案:

答案 0 :(得分:1)

看起来你混淆了这两件事:

Flask会话的一般模式(例如,使用您的密钥签名加密cookie,您必须将secret_key配置集设置为使用这些),如下所示:

from flask import session, redirect, url_for, render_template


@app.route('/login/')
def login():
    # logic to sign in user
    # then set session variable
    session['profile'] = {"user_id": 5, "user_name": "Tom"}

    return redirect(url_for('main'))


@app.route('/logout/')
def logout():
    # logic to sign out user
    # clear session
    session.clear()

    return redirect(url_for('main'))


@app.route('/')
def main():
    user = None
    if 'profile' in session:
        user = session['profile']
    return render_template('index.html', user=user)