简体   繁体   中英

Is it thread-safe to use SQLAlchemy with engine/connections instead of sessions?

I've got a simple webservice which uses SQLAlchemy to connect to a database using the pattern

engine = create_engine(database_uri)
connection = engine.connect()

In each endpoint of the service, I then use the same connection, in the following fashion:

for result in connection.execute(query):
    <do something fancy>

Since Session s are not thread-safe, I'm afraid that connection s aren't either.

Can I safely keep doing this? If not, what's the easiest way to fix it?

Minor note -- I don't know if the service will ever run multithreaded, but I'd rather be sure that I don't get into trouble when it does.

Short answer: you should be fine.

There is a difference between a connection and a Session . The short description is that connections represent just that… a connection to a database. Information you pass into it will come out pretty plain. It won't keep track of your transactions unless you tell it to, and it won't care about what order you send it data. So if it matters that you create your Widget object before you create your Sprocket object, then you better call that in a thread-safe context. Same generally goes for if you want to keep track of a database transaction.

Session , on the other hand, keeps track of data and transactions for you. If you check out the source code , you'll notice quite a bit of back and forth over database transactions and without a way to know that you have everything you want in a transaction, you could very well end up committing in one thread while you expect to be able to add another object (or several) in another.


In case you don't know what a transaction is this is Wikipedia , but the short version is that transactions help make sure your data stays stable. If you have 15 inserts and updates, and insert 15 fails, you might not want to make the other 14. A transaction would let you cancel the entire operation in bulk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM