AttributeError: __enter__ using with statement SqlAlchemy session

AttributeError: __enter__ using with statement SqlAlchemy session

当我尝试像 guide 中那样使用 SQLAalchemy 会话时,我得到了这个 AttributeError: __enter__

我的代码:

Session = scoped_session(sessionmaker(autoflush=True, autocommit=False, bind=engine))
    
@contextmanager
def session_scope():
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

class SomeClass:

    def __init__(self):
        self.session_scope = session_scope

    def something_with_session(self):

        with self.session_scope as session:  # <-- error

我做错了什么?我正在使用 Python 3.6

您必须调用函数来获取上下文

with self.session_scope() as session:
    ...

对于那些习惯使用 SQLAlchemy 1.4 方式的人来说 运行 通过上下文管理器的会话构建/关闭过程如下:

with Session() as session:
    # Do something

如果您得到 AttributeError: __enter__,请检查您环境中的 SQLAlchemy 版本是否真的是 SQLAlchemy>=1.4this answer.

中有更多详细信息