[英]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
)對象不可下標,您不能使用[]
表示法訪問其屬性。 只需直接訪問id
: current_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.