[英]python flask-login: current_user keep anonymous
我正在使用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()仍然會返回失敗。
我不知道在哪里檢查,任何人都可以幫助我嗎?
PS用戶對象是由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')
我完全忘了這件事。 實際上是因為我們使用多緩存服務器。 因此,有時在此服務器中登錄的用戶不會緩存在其他服務器中。 解決了使用sentinel redis。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.