AttributeError:__ enter__使用with语句SqlAlchemy session

时间:2017-04-15 18:48:04

标签: python session sqlalchemy contextmanager

我尝试使用sqlalchemy会话时获取此AttributeError: __enter__,如此guide

我的代码:

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

1 个答案:

答案 0 :(得分:10)

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

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