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")
Asked By: Kingz

||

Answers:

Sessions 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")
Answered By: Fynn Becker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.