Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.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-独立事务_Python_Sqlalchemy - Fatal编程技术网

Python sqlalchemy-独立事务

Python sqlalchemy-独立事务,python,sqlalchemy,Python,Sqlalchemy,我有一个关于炼金术交易的问题 def funca(): instance = MyModel.query.get(5) try: instance.some_field = 'test' instance.do_something() instance.do_something_other() # Let's pretend that this causes exception db.session.commit(

我有一个关于炼金术交易的问题

def funca():
    instance = MyModel.query.get(5)

    try:
        instance.some_field = 'test'
        instance.do_something()
        instance.do_something_other() # Let's pretend that this causes exception
        db.session.commit()
     except Exception:
        db.session.rollback()

# My model method
def do_something(self):
    external_id = self.make_request_to_external_service()
    self.external_id = external_id

# My model method
def do_something_other(self):
    external_details = self.make_another_external_request()
    self.external_details = external_details
我现在如何实现,在异常情况下,这将仅回滚
某些\u字段
外部\u详细信息
更改,并且
外部\u id
仍保存在db中

我可以为这3个操作使用嵌套事务还是手动启动独立事务

这里的问题是,
do\u something
将获得
external\u id
,并且它必须保存在数据库中,因为我不能第二次这样做,而且如果我不回滚此事务
,某些字段将导致我的数据库和外部服务之间的不同步


出于本示例的目的,让我们假设我不能在
实例之前执行
操作
。某些字段='test'
,因为我可以独立运行此字段并提交此字段,但在我的实际应用程序中我不能执行此操作。

将它们放在单独的try…catch中。是否可以使用取决于您使用的数据库。如果是,则使用该选项。