首页 > 解决方案 > Flask SQLAlchemy:AttributeError:用户查询属性为无

问题描述

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

我如何不建立一个普通的网站,我没有使用SQLAlchemySessionUserDatastore,而不是它,我正在使用SQLAlchemyUserDatastore.

问题是当我尝试使用该类时,我无法通过db_user(即对象)查找用户。显示的错误表示该属性为无。SQLAlchemyUserDatastoreUserquery

查找用户示例:

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'`

当我列出用户的属性时,该属性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'`

标签: pythonpython-3.xflaskflask-sqlalchemy

解决方案


推荐阅读