@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,但是由于这段代码对数据库没有任何作用,但是我不知道为什么会这样。
有人知道我在这里做错什么吗?
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'
g.user全局 如果你要注意的话,你会记得在登录视图功能中我们检查g.user以确定用户是否已经登录。要实现此目的,我们将使用before_requestFlask中的事件。before_request每次接收到请求时,所有装饰有功能的函数都会在查看函数之前运行。因此,这是设置g.user变量(文件app/views.py)的正确位置:
g.user
before_requestFlask
before_request
@app.before_request def before_request(): g.user = current_user
这就是全部。在current_user全球是由瓶,登录设置,所以我们只要把复制的g对象有更好的访问。这样,所有请求都可以访问登录的用户,甚至在模板内部也可以。
current_user
你的代码显然缺少此before_request处理程序。