我正在尝试按照Flask Mega Tutorial来学习烧瓶。在part 5中,login()视图的编辑方式如下:
@app.route('/login', methods = ['GET', 'POST'])
@oid.loginhandler
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
session['remember_me'] = form.remember_me.data
return oid.try_login(form.openid.data, ask_for = ['nickname', 'email'])
return render_template('login.html',
title = 'Sign In',
form = form,
providers = app.config['OPENID_PROVIDERS'])
然而,这会给我一个AttributeError,我将在下面粘贴StackTrace。它给出了一个错误,我完全从示例的来源粘贴了一块。我使用PeeWee而不是SQLAlchemy,但由于这段代码没有对DB做任何事情,我不知道为什么会有相关的。
有人知道我在这里做错了吗?
Traceback (most recent call last):
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/flask_openid.py", line 446, in decorated
return f(*args, **kwargs)
File "/Users/kramer65/dev/repos/microblog/app/views.py", line 31, in login
if g.user is not None and g.user.is_authenticated():
File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: '_AppCtxGlobals' object has no attribute 'user'
答案 0 :(得分:35)
同样的教程,稍微进一步解释了如何设置g.user
:
g.user global
如果你正在注意,你会记得在登录视图功能中我们检查
g.user
以确定用户是否已经登录。为了实现这一点,我们将使用Flask的before_request
事件。每次收到请求时,任何用before_request
修饰的函数都将在视图函数之前运行。因此,这是设置g.user
变量(文件app/views.py
)的正确位置:@app.before_request def before_request(): g.user = current_user
这就是全部。
current_user
全局由Flask-Login设置, 所以我们只需在g
对象中放一个副本就可以更好地访问它。 这样,所有请求都可以访问登录用户 内部模板。
您的代码显然缺少此before_request
处理程序。