Using multiple POSTGRES databases and schemas with the same Flask-SQLAlchemy model

二次信任 提交于 2019-12-05 13:33:05

Finally found a solution to this.

Essentially, I didn't create new classes for each database, I just used different database connections for each.

This method on its own is pretty common, the tricky part (which I couldn't find examples of) was handling schema differences. I ended up doing this:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Session = sessionmaker()

class ContentProvider():

    db = None
    connection = None
    session = None

    def __init__(self, center):
        if center == A:
            self.db = create_engine('postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES_A, echo=echo, pool_threadlocal=True)
            self.connection = self.db.connect()
            # It's not very clean, but this was the extra step. You could also set specific connection params if you have multiple schemas
            self.connection.execute('set search_path=A_schema')
        elif center == B:
            self.db = create_engine('postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES_B, echo=echo, pool_threadlocal=True)
            self.connection = self.db.connect()
            self.connection.execute('set search_path=B_schema')

    def get_fra_list(self):
        logging.debug("Fetching fra list")
        fra_list = self.session.query(FRARecord.fra_code)
        return fra_list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!