"""演示连接池耗尽后的超时与释放。""" from __future__ import annotations import tempfile from pathlib import Path from sqlalchemy import Engine, create_engine from sqlalchemy.exc import TimeoutError as PoolTimeoutError def build(path: Path) -> Engine: return create_engine( f"sqlite:///{path}", pool_size=1, max_overflow=0, pool_timeout=0.1, ) def scenario(path: Path) -> tuple[bool, bool]: engine = build(path) first = engine.connect() timed_out = False try: try: second = engine.connect() except PoolTimeoutError: timed_out = True else: second.close() first.close() third = engine.connect() third.close() return timed_out, True finally: engine.dispose() def main() -> None: with tempfile.TemporaryDirectory() as tmp: timed_out, recovered = scenario(Path(tmp) / "pool.sqlite") print(f"timed_out: {timed_out}") print(f"after_release: {recovered}") if __name__ == "__main__": main()