如果用户是匿名的,则获取 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()
并在用户未通过身份验证时显示一条消息。在我不使用 current_user['id']
的其他方法中,如果用户未通过身份验证,我会收到正确的消息。为什么会出现此错误?
def patients(self):
get_doctor_id = str(current_user['id']);
如果您想在 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)
User
(和AnonymousUser
)对象不可订阅,您不能使用[]
表示法访问其属性。只需直接访问 id
:current_user.id
。 Flask-Login 的 UserMixin
也提供了一个 get_id
方法:current_user.get_id()
,默认情况下 returns 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_user['id']
获取当前用户 ID。我得到 TypeError: 'AnonymousUser' object has not attribute __getitem__
即使我在模板中使用 current_user.is_authenticated()
并在用户未通过身份验证时显示一条消息。在我不使用 current_user['id']
的其他方法中,如果用户未通过身份验证,我会收到正确的消息。为什么会出现此错误?
def patients(self):
get_doctor_id = str(current_user['id']);
如果您想在 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)
User
(和AnonymousUser
)对象不可订阅,您不能使用[]
表示法访问其属性。只需直接访问 id
:current_user.id
。 Flask-Login 的 UserMixin
也提供了一个 get_id
方法:current_user.get_id()
,默认情况下 returns 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