python 缺少userloader或request_loader错误

brgchamk  于 2023-11-16  发布在  Python
关注(0)|答案(3)|浏览(146)

我有一个问题与flask-login用户加载器不工作

Exception: Missing user_loader or request_loader. Refer to http://flask-login.readthedocs.io/#how-it-works for more info.

字符串
当我尝试在shell中导入用户模型时:

AttributeError: 'LoginManager' object has no attribute 'load_user'


这是我的代码:

-------------------app/__init__.py----------------

from app.config import Config
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

#create app
app = Flask(__name__)
app.config.from_object(Config)

#init pckages
db = SQLAlchemy(app)
login_manager = LoginManager(app)

#import Blueprints
from app.blueprints.user.routes import user
from app.blueprints.dashboard.routes import dashboard

#register Blueprints
app.register_blueprint(user)
app.register_blueprint(dashboard)

------------------------------app.py-------------------------------
from app import app

if __name__ == "__main__":

    app.run(debug=True)
------------------------------user model------------------------------------
from app import db, login_manager
from flask_login import UserMixin

@login_manager.load_user
def load_user(user):
    return User.get(user)

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(20), unique=True, nullable=False)
    avatar = db.Column(db.String(50), default="default.jpg")
    password = db.Column(db.String(60), nullable=False)

    def __repr__(self):
        return self.username

4szc88ey

4szc88ey1#

装修工应该是
@login_manager.user_loader不是load_user

eblbsuwk

eblbsuwk2#

而不是:

@login_manager.load_user
def load_user(user):
    return User.get(user)

字符串
尝试:

@login_manager.user_loader
def load_user(user):
    return User.query.get(int(user))

dldeef67

dldeef673#

您可以对当前的user模型进行轻微修改。目前,您有:

@login_manager.load_user
def load_user(user):
    return User.get(user)

字符串
想想这个:
1.从flask_login导入LoginManager

from flask_login import LoginManager

login = LoginManager(app)


1.更新user模型如下:

from flask_login import UserMixin
from app import login # the variable from Flask-login

@login.user_loader
def load_user(id):
    return User.query.get(int(id)) # slightly modified such that the user is loaded based on the id in the db

  • user loader* 通过@login.user_loader装饰器在Flask-Login中注册。Flask-Login作为参数传递给函数的id将是一个字符串,因此使用数字ID的数据库需要将字符串转换为整数,如上所述。

相关问题