我正在尝试学习Flask,但是UserMixin似乎无法正常工作

时间:2019-12-09 15:42:35

标签: python inheritance flask flask-login

更确切地说。我目前正在从Corey Schafers教程系列中学习Flask,并且我处于登录身份验证阶段,一切似乎都很好,但是尝试登录后却出现了此错误:

AttributeError
AttributeError: 'User' object has no attribute 'is_active'

Traceback (most recent call last)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\panda\Desktop\HDD\Documents\Code\Python\Flask\flaskblog\routes.py", line 60, in login
login_user(user, remember=form.remember.data)
File "C:\Users\panda\Desktop\HDD\Programs\Python3\Lib\site-packages\flask_login\utils.py", line 158, in login_user
if not force and not user.is_active:

定义了User类的代码如下:

from datetime import datetime
from flaskblog import db, login_manager
from flask_login import UserMixin



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


class User(UserMixin, db.Model):
    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)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)


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

我的 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.secret_key = '5791628bb0b13ce0c676dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
login_manager = LoginManager(app)


bcrypt = Bcrypt(app)
from flaskblog import routes

我的带有登录页面路由的代码如下:

from flaskblog.models import User, Post
from flask import render_template, url_for, flash, redirect
from flaskblog.forms import RegistrationForm, LoginForm
from flaskblog import app, db, bcrypt
from flask_login import login_user

@app.route("/login", methods=['GET', 'POST'])
def login():

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)

最奇怪的部分是,即使我编辑类User以使它本身包含方法“ is_active” ,错误仍会出现

from datetime import datetime
from flaskblog import db, login_manager
from flask_login import UserMixin



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


class User(UserMixin, db.Model):


    def is_active():
        return True


    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)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)


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

此外,如果有帮助,在多台计算机上的多个操作系统上也会发生相同的问题。

1 个答案:

答案 0 :(得分:0)

我认为您的继承顺序有误

尝试通过以下方式创建clear类:

        def absorb_army(self, other):
            for item in other.composition:
                self.composition[item] += other.composition[item]
                other.composition[item] = 0  # Zero after adding to self

在此处查看答案以更详细地了解:How does Python's super() work with multiple inheritance?

请告诉我这是否可行。


编辑1:

看不到LoginManager初始化。按照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(120), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True)