知识卡片
上下文管理器包住资源生命周期
Python 上下文管理器以 with 划定资源使用范围:进入时由 __enter__ 建立并可返回资源,退出时 __exit__ 接收异常信息并执行清理。用于数据库会话时可统一回滚和关闭逻辑,使正常完成与异常退出都经过同一收尾路径。参见 [[工作单元管理本地事务]]。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
原书出处
参考来源
- 位置:《Microservice APIs》第 7 章《Service implementation patterns for microservices》(源文件:_epub-src/OEBPS/Text/07.htm)
- 结论依据:原文解释 `with`、`as`、`__enter__`、`__exit__` 的职责,并以 UnitOfWork 在进入时创建会话、退出时回滚及关闭为例。
- 原始内容:A class-based context manager has an __init__() , an __enter__() , and an __exit__() method . ... __enter__ () —Defines the operations that must be undertaken upon entering the context, such as creating a session or opening a file.