Python 如何使用 Flask 检索会话数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15591620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve session data with Flask?
提问by webminal.org
I have flask+wtforms application. I can see in login() user object stored as
我有烧瓶+wtforms 应用程序。我可以在 login() 用户对象中看到存储为
if user:
if user.verify_password(form.password.data):
flash('You have been logged in')
user.logins += 1
db.session.add(History(user.uid))
db.session.commit()
session['user'] = user
Now I wanted to retrieve the user
现在我想检索用户
if 'user' in session:
User=session.get('user')
print User.nickname ###<< how to retrieve specific object member?
It fails with message like :
它失败并显示如下消息:
Instance <User at 0x8e5a64c> is not bound to a Session; attribute refresh operation cannot proceed
采纳答案by eandersson
It's simple. If you want to retrieve a specific object simply add the name of the variable within session, e.g. session['nickname'].
这很简单。如果您想检索特定对象,只需在会话中添加变量的名称,例如session['nickname'].
You can set the variable the same way, by doing session['nickname'] = nickname.
您可以通过执行相同的方式设置变量session['nickname'] = nickname。
In your case you would change it to the following
在您的情况下,您可以将其更改为以下内容
if 'user' in session:
user = session['user']
print user
if 'nickname' in session:
nickname = session['nickname']
print nickname
This is an simplified version of the function I use for login.
这是我用于登录的函数的简化版本。
@app.route('/login', methods=['POST'])
def login():
"""Authenticate User"""
username = request.form['username'].strip()
nickname = request.form['nickname'].strip()
password = request.form['password']
try:
if Auth().VerifyLogin(username, password):
session['username'] = username
session['nickname'] = nickname
else:
# failed to login, do something.
except Exception as why:
app.logger.critical('.....')

