Reputation: 543
Can anyone tell me how I can view a session variable within flask, so that I can retreive the current logged in user? With my 'for loop' I can view all items iterated, but I need the current logged in user...
Thanks in advance
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')
Upvotes: 0
Views: 3229
Reputation: 5372
It looks like you're confusing these two things:
The general pattern for a Flask session (e.g. signed crypto cookie using your secret key, you must have the secret_key
configuration set to use these) is like this:
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)
Upvotes: 1