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

后端 未结 2 994
生来不讨喜
生来不讨喜 2020-12-13 11:36

I have a Pylons-based web application which connects via Sqlalchemy (v0.5) to a Postgres database. For security, rather than follow the typical pattern of simple web apps (

相关标签:
2条回答
  • 2020-12-13 12:04

    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)()
    
    0 讨论(0)
  • 2020-12-13 12:13

    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

    0 讨论(0)
提交回复
热议问题