python
config_error
ai_generated
true
sqlalchemy.exc.UnboundExecutionError: 无法为 Mapper Mapper[User(users)] 或此 Session 定位绑定。
sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper Mapper[User(users)] or this Session.
ID: python/pytest-sqlalchemy-session-not-bound
80%修复率
87%置信度
0证据数
2024-08-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.0.x | active | — | — | — |
根因分析
创建 SQLAlchemy Session 时未传入 engine(或未将 sessionmaker 绑定到 engine),测试 fixture 产出的 session 在之后对未绑定的 mapper 使用时抛出异常。
English
A SQLAlchemy Session was created without an engine (or sessionmaker bound to engine) and the test fixture yields a session that is later used against an unbound mapper.
解决方案
-
96% 成功率
from sqlalchemy.orm import sessionmaker @pytest.fixture def db(engine): Session = sessionmaker(bind=engine) session = Session() yield session session.close() -
93% 成功率
from sqlalchemy.orm import scoped_session, sessionmaker @pytest.fixture def db(engine): factory = sessionmaker(bind=engine) Session = scoped_session(factory) yield Session() Session.remove()
无效尝试
常见但无效的做法:
-
80% 失败
Rebinding after the session has already executed queries or checked out connections raises InvalidRequestError; also fragile with scoped_session.
-
92% 失败
session.connection() requires a bind in the first place; it raises the same UnboundExecutionError.