我正在尝试使用Flask-Login为Flask设置登录名。我有一个针对用户的CouchDB;客户文档中有一个称为“用户”的对象。
class User(UserMixin):
def __init__ (self, user) :
self.name = user['name']
self.password = user['password']
self.id= user['id']
def is_active(self):
return True
def is_authenticated(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
def check_user(id):
for row in db.query(map_auth):
if row.value['id'] == id:
authUser = User(row.value)
return authUser
else:
return "User not found in database"
@login_manager.user_loader
def load_user(id):
return check_user(id)
@app.route('/login/', methods=['GET','POST'])
def login():
if request.method == 'POST':
for row in db.query(map_auth):
if row.value['name'] == request.form['name'] and row.value['password'] == request.form['password']:
authUser = User(row.value)
flask_login.login_user(authUser)
app.logger.debug(authUser.name)
app.logger.debug(authUser.is_authenticated())
app.logger.debug(authUser.is_active())
return redirect(url_for('protected'))
return render_template('login.html')
map_auth
是来自python-couchdb的视图函数。该视图为用户返回一个JSON列表,其中包含以下信息:{"name": "xxxx", "id":1, "password": "password"}
。
我通过User
在Python Shell中进行仿真来验证该类是否独立工作。在Flask中使用它时,出现以下错误。
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 790, in decorated_view
elif not current_user.is_authenticated:
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'str' object has no attribute 'is_authenticated'
我已经验证了authUser
我使用的对象是否is_authenticated()
正确。
如果用户标识无效,则应返回该user_loader
函数(在您的情况下为in check_user
)None
。在您的情况下,将"User not found in database"
返回一个字符串,这将创建您遇到的异常。
None
如果用户标识无效,则返回。
记录:
如果ID无效,则应返回
None
(不引发异常)。(在这种情况下,将手动从会话中删除该ID,然后继续进行处理。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句