首页 > 解决方案 > SQLAlchemy 对象会话属性错误:__enter__

问题描述

当我在 with 语句中使用 SQLAlchemy 会话时,它不起作用。它应该可以工作,因为根据源代码sessionmaker返回一个对象和方法。我检查了一下,我正在使用最新版本(SQLAlchemy==1.3.22)。Session__enter____exit__

用于查明错误的代码:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    'sqlite:////devdb/sqlite.db',
    echo=True
)

Session = sessionmaker(bind=engine)

with Session() as session:
    print('it worked!')

错误:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    with Session() as session:
AttributeError: __enter__

我也尝试了自己的课程,只是为了测试它,并且发生了同样的错误:

class MySessionMaker(sessionmaker):
    def __init__(self, bind):
        super().__init__(bind=bind)

    def __enter__(self):
        return self()

    def __exit__(self, exception_type, exception_value, exception_traceback):
        self.close()



Session = MySessionMaker(bind=engine)

我在网上找不到关于这个错误的任何信息,有没有其他人遇到过这个问题?

标签: pythonsqlalchemy

解决方案


推荐阅读