Using multiple databases with peewee

I am writing a "multi tenant" application. It will be hosted on different subdomains and based on which subdomain it hosted, it should use a different database.

Is it possible to determine at run time which database to use? If I was using django I would just write a router that takes care of this, but I haven't found anything like peewee.

Did I miss something?

Thank!

PS: hack this How to query multiple similar databases using Peewee? where you need to know ahead of time which class to call will not work well script

+3


source to share


2 answers


Instead of handling this in peewee, you can handle the db selection in flask with app factories from app managers



+2


source


You can also see the ReadSlave module for an example of changing databases at runtime.

code:



class ReadSlaveModel(Model):
    @classmethod
    def _get_read_database(cls):
        if not getattr(cls._meta, 'read_slaves', None):
            return cls._meta.database
        current_idx = getattr(cls, '_read_slave_idx', -1)
        cls._read_slave_idx = (current_idx + 1) % len(cls._meta.read_slaves)
        return cls._meta.read_slaves[cls._read_slave_idx]

    @classmethod
    def select(cls, *args, **kwargs):
        query = super(ReadSlaveModel, cls).select(*args, **kwargs)
        query.database = cls._get_read_database()
        return query

    @classmethod
    def raw(cls, *args, **kwargs):
        query = super(ReadSlaveModel, cls).raw(*args, **kwargs)
        if query._sql.lower().startswith('select'):
            query.database = cls._get_read_database()
        return query

      

+3


source







All Articles