python - 在使用 marshmallow sql-alchemy 对象时避免 DB Session 添加 marshmallow 对象

标签 python flask sqlalchemy flask-sqlalchemy marshmallow

有没有办法在使用 Marshmallow - sqlalchemy 时避免将数据插入 session

sqlalchemy marshmallow 避免加载到 session 中

引用:https://marshmallow-sqlalchemy.readthedocs.org/en/latest/

因为我们试图自己管理对象。如果需要,将添加到 session 中,但为了验证,我需要使用 load()

author = Author(name='Chuck Paluhniuk')
book = Book(title='Fight Club', author=author)
session.add(author)
session.add(book)
session.commit()

author_schema.dump(author).data
# {'books': [123], 'id': 321, 'name': 'Chuck Paluhniuk'}

author_schema.load(dump_data, session=session).data
# <Author(name='Chuck Paluhniuk')>

避免此问题的解决方法是,在我尝试加载后,我可以调用 DB Session.close() 来忽略临时数据。但是我再次需要获取 session 以将数据刷新到 DB 中。

最佳答案

将对象添加到 session 对您的代码没有不良影响。正如你所说,你以后会自己做。所以手动添加和通过load方法添加没有区别。

author = author_schema.load(dump_data, session=session)
# now author has been added to session by load method
# do whatever you want
db.session.commit() # This is enough to write changes you've made
# or if you don't want to save anything just
db.session.rollback()

我真的不明白为什么要阻止通过load的方法将对象添加到 session

关于python - 在使用 marshmallow sql-alchemy 对象时避免 DB Session 添加 marshmallow 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36551337/

相关文章:

Python 反射和类型转换

python - 将多个日期时间格式化为一个字符串

python - Flask 参数转换器 'int' 对象不可调用

python - 如何调查 SQLAlchemy QueuePool 限制溢出?

python - 使用 SQLAlchemy 和 PostgreSQL 的 Flask 单元测试会耗尽数据库连接

python - 将数据框分组并根据条件选择其中一个单元格

python - Windows 解释器上未定义命名元组

python - 在 Flask 中创建一个异步任务

javascript - 在 Flask/Javascript 中获取动态列表元素到服务器

python - 使用 Flask Python 将点几何插入 PostGIS