python - Flask SQLAlchemy:AttributeError:用户查询属性为无
问题描述
我正在为我的 Flask REST API 创建一个数据库连接。
我如何不建立一个普通的网站,我没有使用SQLAlchemySessionUserDatastore
,而不是它,我正在使用SQLAlchemyUserDatastore
.
问题是当我尝试使用该类时,我无法通过db_user
(即对象)查找用户。显示的错误表示该属性为无。SQLAlchemyUserDatastore
User
query
查找用户示例:
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'`
解决方案
推荐阅读
- c++ - 如何将 lambda/std::function/Functor 传递给可变参数函数
- node.js - 访问使用 node.js 和 express.js 构建的 aws beanstalk 域时出现 CONNECTION_REFFUSED 错误
- jquery - jquery:从子元素中选择最近的前一个元素
- flutter - 错误:名称“用户”在库“package:firebase_auth/firebase_auth.dart”和“package:quizmaker/models/user.dart”中定义
- swiftui - SwiftUI:自定义视图修饰符不符合 ViewModifier?
- sql - 与附加字段的一对多关系
- javascript - 我是编码新手,我正在尝试使用多个 || (或)在 javascript 中的 if 语句条件中
- c# - 如何为 TextureRect 着色?
- excel - BDS功能自动写入日期
- file - Kubernetes ConfigMap 挂载单个文件而不是目录