Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用SQLAlchemy contextmanager并仍然获取行ID?_Python_Transactions_Sqlalchemy_Contextmanager - Fatal编程技术网

Python 如何使用SQLAlchemy contextmanager并仍然获取行ID?

Python 如何使用SQLAlchemy contextmanager并仍然获取行ID?,python,transactions,sqlalchemy,contextmanager,Python,Transactions,Sqlalchemy,Contextmanager,我正在使用SQLAlchemy为我处理会话。我不明白的是如何获取自动生成的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(so

我正在使用SQLAlchemy为我处理会话。我不明白的是如何获取自动生成的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
我缺少什么?

用于在当前事务中执行挂起的命令

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
如果在
刷新之后但在会话超出范围之前发生异常,则更改将回滚到事务开始。在这种情况下,您的
soft_文件
实际上不会写入数据库,即使它已经被赋予了一个ID