简体   繁体   English

如何正确实现 Peewee 回滚?

[英]How to Properly Implement Peewee Rollback?

I have a code using TestModel which inherits playhouse.postgres_ext.Model, an instance of PostgreSQL as sql_db , an instance of SMTP as smtp for notification我有一个使用 TestModel 的代码,它继承了 playhouse.postgres_ext.Model,一个 PostgreSQL 实例作为sql_db ,一个 SMTP 实例作为smtp用于通知

@sql_db.atomic()
def update_jersey():
    TestModel.update(TestModel.jersey_number=24).where(TestModel.first_name="kobe").execute()
    smtp.sendmail(*args, **kwargs)

I want my TestModel.update() to rollback when smtp.sendmail() fails but currently, the code doesn't rollback the update.我希望我的 TestModel.update() 在 smtp.sendmail() 失败时回滚,但目前,代码不会回滚更新。

I also tried using the logic below but still, rollback is not working.我也尝试使用下面的逻辑,但仍然无法回滚。

with sql_db.manual_commit():
    sql_db.begin()
    try:
        TestModel.update()
        smtp.sendmail()
    except Exception:
        sql_db.rollback()
    else:
        sql_db.commit()

I also tried the sql_db.transaction() as txn but still no luck.我也试过sql_db.transaction() 作为 txn但仍然没有运气。

How can I implement the rollback given that the Exception is caused by another function and not related to SQL?鉴于异常是由另一个函数引起的并且与 SQL 无关,我该如何实现回滚?

You can see in the tests that the atomic decorator and context-manager will roll-back implicitly if an error occurs in the wrapped-block.您可以在测试中看到,如果包装块中发生错误, atomic装饰器和上下文管理器将隐式回滚。

Docs here:文档在这里:

http://docs.peewee-orm.com/en/latest/peewee/database.html#managing-transactions http://docs.peewee-orm.com/en/latest/peewee/database.html#managing-transactions

Here's a minimal example:这是一个最小的例子:

db = SqliteDatabase(':memory:')

class R(Model):
    value = IntegerField()
    class Meta:
        database = db

db.create_tables([R])

with db.atomic():
    R.create(value=1)

# Explicit rollback
with db.atomic() as txn:
    R.create(value=2)
    txn.rollback()

# Implicit rollback because of exception.
try:
    with db.atomic():
        R.create(value=3)
        4 / 0
except ZeroDivisionError:
    pass

print([x.value for x in R])
# Prints:
# [1]

RIP Kobe RIP神户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM