is it possible to retrieve engine value from a sql alchemy session
Question:
First I create a session as follows:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
some_engine = create_engine('my_engine_string')
Session = sessionmaker(bind=some_engine)
session = Session()
Then I send this session as an argument to a method
def example(session):
print("you created a session!")
Is it possible to get the value of some_engine
from session
inside the example
method? without actually passing some_engine
or my_engine_string
to example
method.
Something as below:
def example(session):
print("you created a session!")
engine = <using session get the value of `some_engine`>
print("the engine is retrieved from session")
Answers:
Session
s have the .get_bind()
method which in your case will return your Engine
instance.
Relevant excerpt from the sqlalchemy docs
:
Return a “bind” to which this Session
is bound.
The “bind” is usually an instance of Engine
, except in the case where
the Session
has been explicitly bound directly to a Connection
.
Thus your example()
function could do something like:
def example(session):
print("you created a session!")
engine = session.get_bind()
print("the engine is retrieved from session")
First I create a session as follows:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
some_engine = create_engine('my_engine_string')
Session = sessionmaker(bind=some_engine)
session = Session()
Then I send this session as an argument to a method
def example(session):
print("you created a session!")
Is it possible to get the value of some_engine
from session
inside the example
method? without actually passing some_engine
or my_engine_string
to example
method.
Something as below:
def example(session):
print("you created a session!")
engine = <using session get the value of `some_engine`>
print("the engine is retrieved from session")
Session
s have the .get_bind()
method which in your case will return your Engine
instance.
Relevant excerpt from the
sqlalchemy docs
:Return a “bind” to which this
Session
is bound.The “bind” is usually an instance of
Engine
, except in the case where
theSession
has been explicitly bound directly to aConnection
.
Thus your example()
function could do something like:
def example(session):
print("you created a session!")
engine = session.get_bind()
print("the engine is retrieved from session")