Flask SQLAlchemy:AttributeError:用户查询属性为None

时间:2019-04-23 15:00:36

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

我正在为Flask REST API创建数据库连接。

我不是在构建普通的网站,而是在使用SQLAlchemySessionUserDatastore,而不是在使用SQLAlchemyUserDatastore

问题是当我尝试使用db_user类时,我无法通过SQLAlchemyUserDatastore(即User对象)寻找用户。 显示的错误表明query属性为None。

查找用户的示例:

user = db_user.find_user(username=username, password=password)
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter_by'`

user = User.query.filter_by(username=username, password=password).all()
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter_by'`

user = User.query.filter(username=username, password=password).all()
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter'`

当我列出User的属性时,属性query存在,但它是None

 >>> dir(User) 
 [..., 'is_authenticated', 'metadata', 'prepare', 'query', 'query_class', 'roles']

 >>> User.query
 None

有人知道会发生什么吗?

我在下面提供了所有代码。

谢谢。

代码:

from catalog import app
from catalog.database import conn

...

app.config['SQLALCHEMY_DATABASE_URI'] = conn
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create database connection
db_connection = SQLAlchemy(app)

# auto map tables
db_connection.Model = automap_base(db_connection.Model)

# models
class User(db_connection.Model, UserMixin):
    __tablename__ = 'user'

    roles = relationship('Role', secondary='role_user',
                         backref=backref('users', lazy='dynamic', cascade='all'), cascade="all, delete-orphan",
                         passive_deletes=True, single_parent=True)


class Role(db_connection.Model, RoleMixin):
    __tablename__ = 'role'


class RoleUser(db_connection.Model):
    __tablename__ = 'role_user'

# datastore
db_user = SQLAlchemyUserDatastore(db_connection, User, Role)

security = Security(app, db_user)

...

# try to look for users by username and password

user = db_user.find_user(username=username, password=password)
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter_by'`

user = User.query.filter_by(username=username, password=password).all()
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter_by'`

user = User.query.filter(username=username, password=password).all()
# it raises: `AttributeError: 'NoneType' object has no attribute 'filter'`

0 个答案:

没有答案