簡體   English   中英

如果用戶匿名,則獲取current_user ['id']

[英]Get current_user['id'] if user is anonymous

我嘗試使用current_user['id']獲取當前用戶ID。 我收到TypeError: 'AnonymousUser' object has not attribute __getitem__即使我在模板中使用current_user.is_authenticated()TypeError: 'AnonymousUser' object has not attribute __getitem__如果用戶未通過身份驗證,則會顯示一條消息。 在其他方法上,當我不使用current_user['id']如果用戶未通過身份驗證,則會收到正確的消息。 為什么會出現此錯誤?

def patients(self):
    get_doctor_id = str(current_user['id']); 

User (和AnonymousUser )對象不可下標,您不能使用[]表示法訪問其屬性。 只需直接訪問idcurrent_user.id Flask-Login的UserMixin提供了一個get_id方法: current_user.get_id() ,默認情況下,該方法為經過身份驗證的用戶返回id ,對於匿名用戶則返回None

確保正確設置用戶類。

from flask_login import UserMixin, AnonymousUserMixin, LoginManager

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...

class AnonymousUser(AnonymousUserMixin):
    id = None  # add an id attribute to the default AnonymousUser

login_manager = LoginManager(app)
login_manager.anonymous_user = AnonymousUser

如果要在current_used為匿名時引發自定義錯誤消息,則可能需要使用try: except:分支

def patients(self):
    try:
        get_doctor_id = str(current_user['id'])
    except TypeError:
        return flask.redirect("http://www.example.com/your/error/page/here", code=302)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM