Multi device user app in Flask App + SQL Alchemy

89 Views Asked by At

I developed a Flask App that uses SQL ALchemy as DB Layer. As it needs user registration and login, added Flask Security Too (https://flask-security-too.readthedocs.io/en/stable/).

The problem that I am facing is that when a user starts multidevice sessions (i.e. logs in on a site, an updates data in other) there is a conflict at SQLAlchemy ORM that finds that the same instance of a model is shared among different data base sessions.

SqlAlchemy: Insert New Row and Modify Another: "Can't attach instance <ObjectT>; another instance with key is already present in this session"

Regarding that, I have studied about merging objects, transition objects, and neither of those seems to be a valid solutions.

Without going into the code, what I am trying to figure out is "which is the strategy that a multi user multi device session needs to have to use SQL Alchemy?"

are using scoped sessions? is SQL ALchemy a good fit? Is there any other alternative to Flask Security Too that avoids facing this kind of problems?

More Data:

My database instantiation:

ONOS_SQLALCHEMY_DATABASE_URI= os.environ.get('BONOS_SQLALCHEMY_DATABASE_URI')

engine = create_engine(BONOS_SQLALCHEMY_DATABASE_URI, pool_size=14)
                           
SessionFactory = scoped_session(sessionmaker(bind=engine))

session = SessionFactory(expire_on_commit=True)

Base = declarative_base()

The code that generates problems when I try to save changes on a session:

class SQLAlchemyDatastore(Datastore):
    def commit(self):
        self.db.session.commit()

    def put(self, model):
        self.db.session.merge(model)
        self.db.session.commit()
        self.db.session.add(model)
        return model
0

There are 0 best solutions below