AttributeError:对象没有属性'user_loader'

时间:2019-10-29 08:45:52

标签: python python-3.x flask flask-sqlalchemy flask-login

我正在使用Flask框架对具有身份验证的网站进行编程。我已经尝试了在互联网上找到的所有解决方案,但没有任何解决方案。

我的第一个想法是,项目结构已损坏。例如缺少其他文件的导入。但这不是我想的问题。

我的models.py文件:

from flask_login import UserMixin, LoginManager
from flaskapp import db, login_manager




@login_manager.user_loader
def get_user(user):
    try:
        return get_id(user)
    except:
        return None


class User(db.Model,UserMixin):
    id          =db.Column(db.Integer, primary_key=True)
    username    =db.Column(db.String(20),unique=True, nullable=False)
    email       =db.Column(db.String(120), unique=True, nullable=False)
    password    =db.Column(db.String(60), nullable=False)
    powerlevel  =db.Column(db.Integer, nullable=False)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return int(self.id)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.powerlevel}')"

我的 init .py文件:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager


app = Flask(__name__)
app.config['SECRET_KEY'] = 'xxx'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)


login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager = login_message_category = 'info'




from flaskapp import routes

使用以下命令运行WebApp时:

export FLASK_APP = run.py DEBUG = TRUE 烧瓶运行

出现以下错误消息:

Traceback (most recent call last):
  File "/home/osboxes/.local/bin/flask", line 11, in <module>
    sys.exit(main())
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 966, in main
    cli.main(prog_name="python -m flask" if as_module else None)
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 1137, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 848, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 305, in __init__
    self._load_unlocked()
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
  File "/home/osboxes/Desktop/HMI/run.py", line 1, in <module>
    from flaskapp import app
  File "/home/osboxes/Desktop/HMI/flaskapp/__init__.py", line 21, in <module>
    from flaskapp import routes
  File "/home/osboxes/Desktop/HMI/flaskapp/routes.py", line 6, in <module>
    from flaskapp.models import User
  File "/home/osboxes/Desktop/HMI/flaskapp/models.py", line 7, in <module>
    @login_manager.user_loader
AttributeError: 'str' object has no attribute 'user_loader'

现在我不知道还有什么问题。 如果我忘记提供解决错误的代码,请告诉我。 谢谢您的帮助!

2 个答案:

答案 0 :(得分:1)

首先,您的User.get_id应该返回unicode而不是int。文档中提到了这一点,并附带了一个示例:

  

此方法必须返回一个唯一标识此用户的unicode,   并且可以用来从user_loader回调中加载用户。注意   必须是unicode-如果ID本身是int或某些   其他类型,则需要将其转换为unicode。 (inofficial extension

因此需要更改为:

def get_id(self):
    return unicode(self.id)

接下来,您的user_loader。从文档中:

  

这将设置用于从会话中重新加载用户的回调。的   您设置的函数应使用用户ID(Unicode)并返回用户   对象,如果用户不存在,则为None。

这意味着将您的user_loader调整为:

@login_manager.user_loader
def get_user(user_id):
    try:
        return User.query.get(int(user_id))
    except:
        return None

此外,您在这里遇到错误,这很可能是错误的直接原因:

login_manager = login_message_category = 'info'

因此,您拿起login_manager并将其替换为内容为'info'的字符串。因此,稍后您的应用尝试访问login_manager.user_loader时会失败,因为字符串'info'没有user_loader方法。

将其更改为以下内容可以修复该错误。尽管上述其他问题也需要实施。

login_manager.login_message_category = 'info'

答案 1 :(得分:0)

您已使用login_manager = LoginManager(app)和配置一起创建对象。内部人员首先创建一个对象,然后分两步配置对象。

login_manager = LoginManager()

login_manager.init_app(app)

有关更多参考,请在此处查看链接[https://flask-login.readthedocs.io/en/latest/]

您可能需要在init.py文件中进行更新。