"are transactions in sqlalchemy thread safe?" Code Answer


the docs for connections and sessions say that neither is thread safe or intended to be shared between threads.

the connection object is not thread-safe. while a connection can be shared among threads using properly synchronized access, it is still possible that the underlying dbapi connection may not support shared access between threads. check the dbapi documentation for details.

the session is very much intended to be used in a non-concurrent fashion, which usually means in only one thread at a time.

the session should be used in such a way that one instance exists for a single series of operations within a single transaction.

the bigger point is that you should not want to use the session with multiple concurrent threads.

there is no guarantee when using the same connection (and transaction context) in more than one thread that the behavior will be correct or consistent.

you should use one connection or session per thread. if you need guarantees about the data, you should set the isolation level for the engine or session. for web applications, sqlalchemy suggests using one connection per request cycle.

this simple correspondence of web request and thread means that to associate a session with a thread implies it is also associated with the web request running within that thread, and vice versa, provided that the session is created only after the web request begins and torn down just before the web request ends.

By Olcay Ertas on June 27 2022

Answers related to “are transactions in sqlalchemy thread safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.