Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: __enter__ using with statement SqlAlchemy session

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

like image 607
w33zel Avatar asked Apr 15 '17 18:04

w33zel


People also ask

What does AttributeError __ enter __ mean?

An AttributeError: __enter__ is a common Python error that indicates that a Python object has failed to instantiate with the expected class. The error usually occurs when a class hasn't been imported correctly. Also, it can occur if the user has forgotten to call the parent class in the class definition.

What does Session commit do?

Session. commit() is used to commit the current transaction. It always issues Session. flush() beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting.


2 Answers

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.

like image 86
swimmer Avatar answered Sep 19 '22 11:09

swimmer


You have to call the function to get the context

with self.session_scope() as session:
    ...
like image 21
tdelaney Avatar answered Sep 20 '22 11:09

tdelaney