Are transactions on SQLAlchemy thread safe?

I am developing a web application using SQLAlchemy expression language and not his orm. I want to use multiple threads in my application, but I'm not sure about thread safety. I am using this section of the documentation to establish a connection. I think this is thread safety because I am referencing a specific connection in every request. Is this thread safe?

+3


source to share


2 answers


The docs for connections and sessions say that none of them are thread safe or intended to be shared between threads.

The Connection object is not thread safe. Although the connection can be shared with threads using properly timed access, it is still possible that the underlying DBAPI connection may not support sharing between threads. See the DBAPI documentation for details.

A session is very much intended to be used in a non-competitive module, which usually means only one thread at a time.

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

The more you don't want to use a session with multiple concurrent threads.



When using the same connection (and transaction context) across multiple threads, there is no guarantee that the behavior will be correct or consistent.

You must use one connection or session per stream. If you need data guarantees, you must set the isolation level for the motor or session. For web applications, SQLAlchemy suggests using one connection for each query loop.

This simple correspondence between a web request and a stream means that to associate a session with a stream means that it is also associated with a web request being executed within that thread, and vice versa, provided that the session is only created after the start of the web request and is dropped just before completion of the web request.

+3


source


I think you are mixing atomicity with isolation.

Atomicity is usually handled by transactions and is related to integrity.



Isolation is parallel read / write to a database table (thus thread safety). For example: if you want to increase the value of the int field of the table record, you need select

the record field, increase the value and update

. If multiple threads are doing this at the same time, the result will depend on the read / write order.

http://docs.sqlalchemy.org/en/latest/core/engines.html?highlight=isolation#engine-creation-api

+3


source







All Articles