我有一个使用烧瓶登录的简单设置,如下所示。当我点击 before_request 时,g.user 设置正确。我也在正确注册用户(因为他们使用正确的电子邮件/通行证访问数据库)。我的问题是在 before_request 和页面命中之间,g.user 总是变为无。我想我在会话中遗漏了一些东西,但我不知道是什么。
初始化:
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
在 view/login.py 文件中,我有以下内容。
视图/login.py:
@app.lm.user_loader
def load_user(id):
return models.user.user_with_id(id)
@app.before_request
def before_request():
g.user = current_user
print 'current_user: %s, g.user: %s, leaving bef_req' % (current_user, g.user)
@app.route('/login', methods=['GET', 'POST'])
def login():
print 'in login, g.user: %s' % g.user
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
enter_form = app.forms.EnterForm()
if enter_form.validate_on_submit():
session['remember_me'] = True
return app.models.user.try_register(enter_form.email.data,
enter_form.password.data)
return render_template('index.html', enter_form=enter_form, profiles=[])
意见/index.py:
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
print 'in index, g.user: %s' % g.user
if not g.user:
return redirect(url_for('login'))
return render_template('index.html')
模型/用户.py:
def try_login(email, password, remember_me):
u = user_with_email(email)
if u and authenticate(u, password):
login_user(u, remember=remember_me)
return app.views.index.go_to_index()
def try_register(email, password, role=ROLE_USER):
if not user_with_email(email):
add_user(password, role=role, email=email)
return try_login(email, password)