15

I'm getting this AttributeError: __enter__ when I try to use SQLAalchemy session like in this guide.

My code:

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

What am I doing wrong? I'm using Python 3.6

bad_coder
  • 11,289
  • 20
  • 44
  • 72
w33zel
  • 175
  • 1
  • 1
  • 8

2 Answers2

14

You have to call the function to get the context

with self.session_scope() as session:
    ...
tdelaney
  • 73,364
  • 6
  • 83
  • 116
9

For those used to SQLAlchemy 1.4 way of running the session construction / close process via context manager like so:

with Session() as session:
    # Do something

If you are getting AttributeError: __enter__, check that the SQLAlchemy version in your environment is really SQLAlchemy>=1.4. More details in this answer.

swimmer
  • 1,971
  • 2
  • 17
  • 28
  • 1
    Up voted for the ref to version compatibility. Was running 1.3 on an old environment and wondering why it wasn't working. – EnE_ Jan 25 '22 at 04:35