我正在使用nsidnev/现实世界-示例-应用程序。
我需要将事务逻辑应用于这个项目。
在一个API中,我从存储库调用许多方法,并在许多表中进行更新、插入和删除操作。如果这些操作中都有异常,我如何回滚更改?(或者,如果一切都正确,那么提交。)
发布于 2021-11-19 16:23:29
使用交易记录有两种方法。
1. async with语句
async with conn.transaction():
await repo_one.update_one(...)
await repo_two.insert_two(...)
await repo_three.delete_three(...)
# This automatically rolls back the transaction:
raise Exception2. start、rollback、commit语句
tx = conn.transaction()
await tx.start()
try:
await repo_one.update_one(...)
await repo_two.insert_two(...)
await repo_three.delete_three(...)
except:
await tx.rollback()
raise
else:
await tx.commit()在路由中获取连接conn
注射conn: Connection = Depends(_get_connection_from_pool)。
from asyncpg.connection import Connection
from fastapi import Depends
from app.api.dependencies.database import _get_connection_from_pool
@router.post(
...
)
async def create_new_article(
...
conn: Connection = Depends(_get_connection_from_pool), # Add this
) -> ArticleInResponse:https://stackoverflow.com/questions/70002709
复制相似问题