python - 如何使用 SQLAlchemy contextmanager 并仍然获得行 ID?

标签 python transactions sqlalchemy contextmanager

我正在使用 SQLAlchemy 的 provided contextmanager为我处理 session 。我不明白的是如何获取自动生成的 ID,因为(1)直到调用 commit() 之后才创建 ID(2)新创建的实例仅在上下文管理器的范围:

def save_soft_file(name, is_geo=False):
    with session_scope() as session:
        soft_file = models.SoftFile(name=name, is_geo=is_geo)
        session.add(soft_file)
        # id is not available here, because the session has not been committed
    # soft_file is not available here, because the session is out of context
    return soft_file.id

我错过了什么?

最佳答案

使用session.flush()在当前事务中执行挂起的命令。

def save_soft_file(name, is_geo=False):
    with session_scope() as session:
        soft_file = models.SoftFile(name=name, is_geo=is_geo)
        session.add(soft_file)
        session.flush()
        return soft_file.id

如果在 flush 之后但在 session 超出范围之前发生异常,更改将回滚到事务的开头。在那种情况下,您的 soft_file 实际上不会写入数据库,即使它已被赋予 ID。

关于python - 如何使用 SQLAlchemy contextmanager 并仍然获得行 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28946467/

相关文章:

python - 查找两个非常大的列表之间的差异

python - 执行 Linux shell 脚本

java - 如何在 Hibernate 中记录数据库事务的开始和完成

python - sqlalchemy 过滤器中的安全参数绑定(bind)

python - 未在 sqlalchemy 中提交列更新(sqlalchemy-utils)

python - 从 Flask-SQLAlchemy 获取 UTC 格式的日期时间字段

python - 如何将PNG图像转换为透明GIF?

python - 如何轻松解决分配优化任务

java - 尽可能以交易方式发送邮件

c# - C# 中的对象事务