def ensure_session(engine_or_session):
if isinstance(engine_or_session, Engine):<EOL><INDENT>engine_id = id(engine_or_session)<EOL>if id(engine_id) in session_klass_cache: <EOL><INDENT>SessionClass = session_klass_cache[engine_id]<EOL><DEDENT>else:  <EOL><INDENT>SessionClass = sessionmaker(bind=engine_or_session)<EOL><DEDENT>ses = SessionClass()<EOL>auto_close = True<EOL>return ses, auto_close<EOL><DEDENT>elif isinstance(engine_or_session, Session):<EOL><INDENT>ses = engine_or_session<EOL>auto_close = False<EOL>return ses, auto_close<EOL><DEDENT>
If it is an engine, then create a session from it. And indicate that
this session should be closed after the job done.

:type engine_or_session: Union[Engine, Session]
:rtype: Tuple[Session, bool]