-
-
Notifications
You must be signed in to change notification settings - Fork 896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create an easy way of selecting bindings for db.session() #107
Comments
You could use the bind or mapper argument (in case your class/mapper has a certain bind). I'm not sure what all the different strategies are though, but what works for me is this: |
👍 @mitsuhiko What's the correct way to do this? |
This works but is pretty crappy:
This would be nice:
|
Here's a little workaround I'm using...
Then you can do this:
|
My approach was much like @fogleman 's but. import flask.ext.sqlalchemy
class SQLAlchemySessions(flask.ext.sqlalchemy.SQLAlchemy):
def init_app(self, app):
ret = flask.ext.sqlalchemy.SQLAlchemy.init_app(self, app)
options = {'scopefunc': flask.ext.sqlalchemy.connection_stack.__ident_func__}
self._sessions_ = {}
for bn in app.config.get('SQLALCHEMY_BINDS',{}).keys():
options['bind_key'] = bn
self._sessions_[bn] = self.create_scoped_session(options)
setattr(self, 's_'+bn, self._sessions_[bn])
# Straight from flask-sqlalchemy 2.0
if hasattr(app, 'teardown_appcontext'):
teardown = app.teardown_appcontext
elif hasattr(app, 'teardown_request'):
teardown = app.teardown_request
else:
if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
raise RuntimeError("Commit on teardown requires Flask >= 0.7")
teardown = app.after_request
@teardown
def shutdown_sessions(response_or_exc):
if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
if response_or_exc is None:
for s in self._sessions_.values():
s.commit()
for s in self._sessions_.values():
s.remove()
return response_or_exc
return ret
def create_session(self, options):
bind_key = options.pop('bind_key', None)
if bind_key:
options['bind'] = self.get_engine(self.get_app(), bind_key)
return flask.ext.sqlalchemy.SignallingSession(self, **options) The class creates automatically s_ sessions on the object. |
@franklx this should be merged |
I just used So, I guess we're good? :-) |
See https://github.com/pallets/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py#L735 In the definition of If the above is the right way to get session for a specified bind key, it should be documented. |
The suggested solutions did not work for me.
|
As far as I'm aware, there is no easy way to switch between bindings for executing raw SQL statements:
It's certainly possible that I'm not finding this functionality. However if it doesn't already exist, I believe some way to switch/select bindings for sessions is a pretty necessary feature:
or
Any thoughts?
The text was updated successfully, but these errors were encountered: