With sqlalchemy how to dynamically bind to database engine on a per-request basis With sqlalchemy how to dynamically bind to database engine on a per-request basis postgresql postgresql

With sqlalchemy how to dynamically bind to database engine on a per-request basis


Binding global objects (mappers, metadata) to user-specific connection is not good way. As well as using scoped session. I suggest to create new session for each request and configure it to use user-specific connections. The following sample assumes that you use separate metadata objects for each database:

binds = {}finance_engine = create_engine(url1)binds.update(dict.fromkeys(finance_metadata.sorted_tables, finance_engine))# The following line is required when mappings to joint tables are used (e.g.# in joint table inheritance) due to bug (or misfeature) in SQLAlchemy 0.5.4.# This issue might be fixed in newer versions.binds.update(dict.fromkeys([Employee, Customer, Invoice], finance_engine))staff_engine = create_engine(url2)binds.update(dict.fromkeys(staff_metadata.sorted_tables, staff_engine))# See comment above.binds.update(dict.fromkeys([Project, Hour], staff_engine))session = sessionmaker(binds=binds)()


I would look at the connection pooling and see if you can't find a way to have one pool per user.You can dispose() the pool when the user's session has expired