SQLAlchemy using the same session across threads in the same async function
See original GitHub issueDescribe your question The question basically boils down to whether the following is safe, assuming there is a new SQLAlchemy session s being created every time this function is invoked:
async def func(s: Session):
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, some_func, s)
await loop.run_in_executor(None, some_other_func, s)
...
I’m thinking that it is safe because even though the session is used in (potentially) two different threads in the two run_in_executor calls, those two calls are not concurrent, since the second call won’t be executed until the first one completes. This means the session is not accessed concurrently. Am I right in thinking that?
I asked the same question on Stackoverflow here: https://stackoverflow.com/questions/65650198/sqlalchemy-using-the-same-session-across-threads-in-the-same-async-function. But I feel like I may be able to get a faster response here.
Thanks so much!
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (4 by maintainers)
hey there -
yes your thinking is correct, the Session will be used in threads but as long as it isn’t used concurrently in more than one thread (or greenlet, or whatever), it should be fine.
if you are using the SQLite backend, there are some extra things to take into consideration, you probably have to set the “check_same_thread” flag to False, there’s some background on this at https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#threading-pooling-behavior .
Ok, thx for the explanation. I don’t think we are going to use the same async session or connection on different event loops once we adopt 1.4. From what I understand the web framework we are using won’t create two event loops.