当用户登录到我的示例应用程序时,我将用户名键添加到会话对象中,并将用户对象挂在全局“g”对象之外。见下文。
@app.route('/login/', methods=['GET', 'POST'])
def login():
"""Logs the user in."""
error = None
if request.method == 'POST':
print("login hit")
user = get_user(request.form['username'])
if user is None:
error = 'Invalid username'
print error
elif not check_password_hash(user.password, request.form['password']):
error = 'Invalid password'
print error
else:
flash('You were logged in')
print "logged in"
session['username'] = request.form['username']
g.user = request.form['username']
print error, "error"
return redirect(url_for('main'))
现在,如果用户成功登录(正在发生的事情),他将重定向到主页。这将拆除旧的请求并产生一个新的请求。问题是当一个新请求开始时会话被擦除。我正在打印会话密钥,它们都是空的。这只发生在heroku上,而不是我的本地机器上。我究竟做错了什么。
@app.before_request
def before_request():
print session.keys(), session.values() # shows [] []
print("before request")
print ('username' in session, "in session?")
g.db = connect_db()
g.user = None
if "username" in session:
g.user = get_user(session['username'])