flask-sqlalchemy
flask-sqlalchemy copied to clipboard
is there a good way to get session for different bind/database
Hi,
I need to bind multiple databases, and there is a good way to do it as follow document. https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/
but, after that, sometimes I want to run a plain-text SQL directly via Session for different databases/bind. I ready the source code in this project, and implatment it like this.
@contextmanager
def session_scope(bind='default'):
if bind != 'default':
s = db.create_scoped_session(options={'bind': db.get_engine(db.get_app(), bind)})
else:
s = db.session
s.expire_on_commit = False
try:
yield s
s.commit()
except:
s.rollback()
raise
finally:
s.close()
I want to know if there is a more graceful way to get a session, if not, I suggest adding a function in class SQLAlchemy.
def get_session_by_bind(self, bind=None):
if bind:
return self.create_scoped_session(options={'bind': self.get_engine(self.get_app(), bind)})
else:
return self.session
B&R