大家好!我正在使用Flask建立一个网站。但是当我打开127.0.0.1:5000时,它返回AttributeError:'Anonymousidentity'对象没有属性'name'。匿名身份在flask.ext.principal中定义。我已经阅读了flask-principal / init .py,其中匿名身份定义,没有属性'name',也没有在'Identity'类中。
我是初学者,不知道问题出在哪里。愿有人可以帮助我,任何建议也值得赞赏! :)
以下是帐户/ service.py。 def current_user(identity = None)中发生错误,返回models.User.query.get(identity.name)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from __future__ import unicode_literals
from flask import current_app, g, render_template
from flask.ext.mail import Message
from flask.ext.principal import identity_changed, identity_loaded
from flask.ext.principal import Identity, AnonymousIdentity
from flask.ext.principal import RoleNeed, UserNeed
from ..extensions import db, mail
from ..permissions import roles
from . import models, account
get_appobj = lambda: current_app._get_current_object()
# -------------------------------
# Login and Logout (Authenticate)
# -------------------------------
def login(user):
"""User login."""
identity_changed.send(get_appobj(), identity=Identity(user.id))
def logout():
"""User logout."""
identity_changed.send(get_appobj(), identity=AnonymousIdentity())
def current_user(identity=None):
identity = identity or g.identity
return models.User.query.get(identity.name)
@account.app_context_processor
def account_context_processor():
return {'current_user': current_user}
@identity_loaded.connect
def on_identity_loaded(sender, identity):
"""Load the roles for identity user."""
user = current_user(identity)
if user:
identity.provides.add(UserNeed(user.id))
identity.provides.add(roles.login)
if user.is_actived:
identity.provides.add(roles.authenticated)
if user.is_admin:
identity.provides.add(roles.admin)
if user.is_branch:
identity.provides.add(roles.branch)
# ------------------------------
# Sign Up and Email Confirm User
# ------------------------------
def send_confirm_mail(user):
"""Send a confirm mail for signing up user."""
if user.is_actived:
raise models.UserAcitvedError(user) # only provide for unactived user
with user.permissions['send_confirm_mail'].require(403):
message = Message("grasu",
sender="no-reply@grasu.edu.cn",
recipients=[user.email])
message.html = render_template("mail/activeuser.html",
userid=user.id,
token=user.active_token)
mail.send(message)
def signup(user):
"""Sign up a user."""
# check unique
users = models.User.query
identity_existed = users.filter_by(email=user.email).count()
nickname_has_been_used = users.filter_by(nickname=user.nickname).count()
if identity_existed:
raise IdentityExistedError
if nickname_has_been_used:
raise NicknameUsedError
# write into database
db.session.add(user)
db.session.commit()
# login and send mail
login(user)
send_confirm_mail(user)
# ----------
# Exceptions
# ----------
class IdentityExistedError(Exception):
"""User's email has existed in database."""
class NicknameUsedError(Exception):
"""User's nickname has been used."""
答案 0 :(得分:2)
正如您所注意到的,没有name
属性。而是使用id
属性。
return models.User.query.get(identity.id)