AMNevess
AMNevess

Reputation: 81

Python - SQLAlchemy multiple sessions

I am working on a system which uses SQLAlchemy to read/write to a MySQL database. I have a Factory which makes multiple repositories each one with his own session. I read the documentation os SQLAlchemy and it states that one session should not be used by different processes.

I cannot use same session as it the code will run on different machines.

My question is, is it a good practice to make different sessions? Will it have concurrency problems or races?

Example: If i have 2 sessions writing multiple records to the db, and have a collision of a record. Will the session.commit() abort everything?

Upvotes: 5

Views: 14871

Answers (1)

ZZ ll
ZZ ll

Reputation: 196

SQLAlchemy sessions are light-weight objects so no trouble to create many sessions, and you have to use multiple sessions when you use multiple processes or multiple threads because a session cannot be shared between processes nor threads.

If there is a collision between 2 sessions, then the collision will be raised on session.commit or session autocommit depending on session configuration.

It's better to use sessions with transactions to ensure atomicity property:

session = get_session()
with session.begin():
    session.add(db_obj0)
    session.add(db_obj1)

both db_obj0 and db_obj1 will be created or none.

Upvotes: 7

Related Questions