AttributeError: Object has no attribute 'user_loader'

丶灬走出姿态 提交于 2021-02-11 14:40:56

问题


I'm programming a Website with Authentification while using the Flask Framework. I've tried every solution that i found on the internet but nothing worked for me.

My first idea was, that the Project Structure was corrupt. e.g. missing imports from other files. But thats not the problem i think.

My models.py File:

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}')"

My init.py File:

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

When running the WebApp using:

export FLASK_APP=run.py DEBUG=TRUE flask run

Following Error Message Occurs:

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'

Right now i don't know what else could be the problem. If i forgot to supply some code for solving the error, let me know. Thank you for your Help!


回答1:


First, your User.get_id should be returning unicode not an int. The documentation mentions this, along with an example:

This method must return a unicode that uniquely identifies this user, and can be used to load the user from the user_loader callback. Note that this must be a unicode - if the ID is natively an int or some other type, you will need to convert it to unicode. (Your User Class)

So that needs to be changed to:

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

Next up, your user_loader. From the docs:

This sets the callback for reloading a user from the session. The function you set should take a user ID (a unicode) and return a user object, or None if the user does not exist.

Which would mean adjusting your user_loader to be something like:

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

Also, you have an error here, which is likely the direct cause of the error:

login_manager = login_message_category = 'info'

So your taking your login_manager and replacing it with a string with the contents 'info'. So later when your app tries to access login_manager.user_loader it's failing, because a string 'info' doesn't have a user_loader method.

Changing it to the below should fix the error. Though the other issues addressed above also need to be implemented.

login_manager.login_message_category = 'info'



回答2:


You have used the login_manager = LoginManager(app) you are creating an object along with the configuration. Insider of that create an object first and configure the object in 2 steps.

login_manager = LoginManager()

login_manager.init_app(app)

for more reference please check the link here[https://flask-login.readthedocs.io/en/latest/]

you may need to update in your init.py file.



来源:https://stackoverflow.com/questions/58603924/attributeerror-object-has-no-attribute-user-loader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!