Multi-tenancy with SQLAlchemy

后端 未结 3 430
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 09:36

I\'ve got a web-application which is built with Pyramid/SQLAlchemy/Postgresql and allows users to manage some data, and that data is almost completely independent for differ

3条回答
  •  清歌不尽
    2020-12-28 10:11

    After pondering on jd's answer I was able to achieve the same result for postgresql 9.2, sqlalchemy 0.8, and flask 0.9 framework:

    from sqlalchemy import event
    from sqlalchemy.pool import Pool
    @event.listens_for(Pool, 'checkout')
    def on_pool_checkout(dbapi_conn, connection_rec, connection_proxy):
        tenant_id = session.get('tenant_id')
        cursor = dbapi_conn.cursor()
        if tenant_id is None:
            cursor.execute("SET search_path TO public, shared;")
        else:
            cursor.execute("SET search_path TO t" + str(tenant_id) + ", shared;")
        dbapi_conn.commit()
        cursor.close()
    

提交回复
热议问题