2013-04-16 84 views
3

我使用燒瓶登錄併發生此問題。python燒瓶登錄:current_user保持匿名

運行如下的登錄功能:

@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 

我已經打印出檢查,上述用戶回報corrent,它只是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('[email protected]') 
+0

你在'current_user'類中定義了什麼基類? – namit

+1

你能告訴我們你的[user loader](http://pythonhosted.org/Flask-Login/#how-it-works)回調定義嗎? – DazWorrall

+0

你是否實現了這些? http://pythonhosted.org/Flask-Login/#your-user-class – Paco

回答

0

我完全忘了這件事。 實際上是因爲我們使用了多緩存服務器。所以有時在這臺服務器上登錄的用戶不會緩存在其他服務器上。 解決使用sentinel redis。