我正在使用flask-login,会出现此问题。
登录功能如下:
@api.route('/login', methods=['POST'])
def login():
if current_user.is_authenticated():
return jsonify(flag='success')
username = request.form.get('username')
password = request.form.get('password')
if username and password:
user, authenticated = fsUser.authenticate(username, password)
if user and authenticated:
if login_user(user, remember='y'):
print 'is authenticated: ',current_user.is_authenticated()
return jsonify(flag='success')
current_app.logger.debug('login(api) failed, username: %s.' % username)
return jsonify(flag='fail', msg='Sorry, try again.')
代码工作得很好。它甚至朝着返回标志='成功'运行。 我检查并看到它创建的会话。 除了current_user仍然是匿名的以外,所有工作都很顺利。所以current_user.is_authenticated()仍然会返回失败。
我不知道在哪里检查,有人可以帮助我吗?
P.S。 SQLAlchemy从SQL数据库获取用户对象。如果它可能是问题的根源,我可以在稍微修改后提供model.py.
编辑:我的用户回调定义:
@login_manager.user_loader
def load_user(id):
user = cache.get(id)
if not user:
user = User.get_by_id(id)
cache.set(id, user, 20*60)
return user
我打印出来检查,上面的用户返回是正确的,它只是current_user仍为匿名对象的默认值
用户类:
class User(db.Model, UserMixin):
__tablename__ = 'my_users'
id = Column('user_id', db.Integer, primary_key=True)
level = Column('user_level', db.Integer, nullable=False)
name = Column('user_name', db.String(255))
email = Column('user_email', db.String(255), nullable=False, unique=True)
# ===============================================================
# Users
# ================================================================
# Password
_password = Column('user_password', db.String, nullable=False)
def _get_password(self):
return self._password
def _set_password(self, password):
self._password = generate_password_hash(password)
# Hide password encryption by exposing password field only.
password = db.synonym('_password',
descriptor=property(_get_password,
_set_password))
def check_password(self, password):
if self.password is None:
return False
return check_password_hash(self.password, password)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def find_user(self):
return unicode('hahaha@gmail.com')
答案 0 :(得分:0)
我完全忘了这件事。 实际上是因为我们使用多缓存服务器。因此,有时在此服务器中登录的用户不会缓存在其他服务器中。 解决了使用哨兵redis。