In Python 2.7, it knows to switch to different thread whenever it starts waiting on IO. And, it will check if it needs to switch threads every 100 bytecode instructions.
Updated 2026-07-16: updated the answer and links for SQLAlchemy 2.0.
Session.execute runs its statement within the current transaction, and SQLAlchemy’s autobegin starts that transaction on first use.
So if the statement writes (INSERT, UPDATE, DELETE), yes, you need to commit(), or the transaction rolls back when the session closes. A read-only SELECT changes nothing, so there is nothing to commit.
Here’s a code example along with the output from echo=True, showing the session begins a transaction but doesn’t end it until you run session.commit():
1_sqlalchemy_session_execute.py:
fromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportscoped_session,sessionmakerengine=create_engine('mysql://root@localhost/test')db_session=scoped_session(sessionmaker(bind=engine))db_session.execute('''
INSERT INTO user (first_name, last_name, username, email)
VALUES ("blah", "blah", "blah", "blah@blah.com");
''')
2_output.txt:
2017-01-16 22:54:11,788 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2017-01-16 22:54:11,788 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,790 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2017-01-16 22:54:11,790 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,791 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8' and `Collation` = 'utf8_bin'
2017-01-16 22:54:11,791 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,792 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2017-01-16 22:54:11,792 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,793 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2017-01-16 22:54:11,793 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,794 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin AS anon_1
2017-01-16 22:54:11,794 INFO sqlalchemy.engine.base.Engine ()
2017-01-16 22:54:11,795 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2017-01-16 22:54:11,796 INFO sqlalchemy.engine.base.Engine
INSERT INTO user (first_name, last_name, username, email)
VALUES ("blah", "blah", "blah", "blah@blah.com");
2017-01-16 22:54:11,796 INFO sqlalchemy.engine.base.Engine ()
Before SQLAlchemy 1.1.4, if you wanted to stream your MySQL query using server side cursors, you would need to run your query using execution_options(stream_results=True) and pass SSCursor into create_engine’s connect_args. Now, all you need to do is pass server_side_cursors=True into create_engine and it will automatically stream the results for your select queries. SQLAlchemy 1.4 deprecated server_side_cursors in favor of stream_results=True.
If your application has the potential to run in multiple threads, then you absolutely should use scoped_session. A Session isn’t safe to share across threads, and scoped_session makes sure each thread gets its own.
fromsqlalchemy.ormimportscoped_session,sessionmakerSession=scoped_session(sessionmaker(bind=engine))session=Session()# the same session everywhere in this thread
It’s a registry keyed on the current thread by default. Every call to Session() from the same thread hands back the same object, so you can get at the session deep inside a function without threading one down through every caller, and another thread gets its own instead of stepping on yours.
You do have to call Session.remove() when the unit of work is finished, otherwise the session stays in the registry along with every object in its identity map. Web frameworks usually hook that into the end of a request. Flask-SQLAlchemy sets all of this up for you, so if you’re using that you already have a scoped session.
If your application is single threaded and you’re already passing one session around explicitly, you don’t need it.
If you’re using scoped_session and not explicitly running session.remove(), then your connections will only be returned to the pool after your thread finishes and garbage collection occurs. It’s not a good idea to leave this to garbage collection, because you can’t guarantee your connections will be returned to the pool when your application is busy. This will often lead to errors like this: “TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30”
Another alternative is not making the session global and using a context manager, as described at the bottom of this section: http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it However, this can make things difficult when you need to access the query results outside of the context manager. If you access the query results outside of the context manager without running session.expunge_all(), you’ll see all kinds of errors like this: “DetachedInstanceError: Instance <ReportingJob at 0xa41cd8c> is not bound to a Session; attribute refresh operation cannot proceed”
In new relic transaction logs, I was seeing some PHP requests last as long as an hour. It turns out that time spent waiting on sockets doesn’t apply toward max_execution_time, and loops that involved waiting on sockets could end up taking a really long time without timing out.
PHP docs have this to say about max_execution_time:
“The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.”
The solution ended up being setting request_terminate_timeout in php-fpm.
If your application is threaded and you’re getting a “KeyError” while using the non-decorator version of cachetool’s LRUCache, then you need to put whatever is manipulating the cache object inside of a lock. Also, since LRUCache is modified when values are gotten from it, you will also need to make sure you’re locking when you get values from cache too. If you can use the decorator version of LRUCache, that’s preferred since it has built-in locking.
Here’s an example of the error:
[2016-08-10 22:36:30 +0000] [1] [ERROR] [blah/blah_user] "my_key"
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/thriftpy/server.py", line 92, in handle
self.processor.process(iprot, oprot)
File "/usr/local/lib/python3.4/site-packages/thriftpy/thrift.py", line 244, in process
self.handle_exception(e, result)
File "/usr/local/lib/python3.4/site-packages/thriftpy/thrift.py", line 241, in process
result.success = call()
File "/usr/local/lib/python3.4/site-packages/thriftpy/thrift.py", line 205, in call
*(args.__dict__[k] for k in api_args)
File "/opt/service/blah/dispatcher.py", line 932, in get
return blah.to_thrift()
File "/opt/service/blah/model.py", line 383, in to_thrift
profile = self.profile
File "/opt/service/blah/model.py", line 360, in profile
return service_callers.get_profile(TProfileIdentifiers(id=str(self.profile_id)))
File "/opt/service/blah/util.py", line 121, in func_wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.4/site-packages/dogpile/cache/region.py", line 1053, in decorate
should_cache_fn)
File "/usr/local/lib/python3.4/site-packages/dogpile/cache/region.py", line 657, in get_or_create
async_creator) as value:
File "/usr/local/lib/python3.4/site-packages/dogpile/core/dogpile.py", line 158, in __enter__
return self._enter()
File "/usr/local/lib/python3.4/site-packages/dogpile/core/dogpile.py", line 98, in _enter
generated = self._enter_create(createdtime)
File "/usr/local/lib/python3.4/site-packages/dogpile/core/dogpile.py", line 149, in _enter_create
created = self.creator()
File "/usr/local/lib/python3.4/site-packages/dogpile/cache/region.py", line 630, in gen_value
self.backend.set(key, value)
File "/usr/local/lib/python3.4/site-packages/dogpile/cache/backends/memory.py", line 76, in set
self._cache[key] = value
File "/usr/local/lib/python3.4/site-packages/cachetools/lru.py", line 19, in __setitem__
cache_setitem(self, key, value)
File "/usr/local/lib/python3.4/site-packages/cachetools/cache.py", line 51, in __setitem__
self.popitem()
File "/usr/local/lib/python3.4/site-packages/cachetools/lru.py", line 33, in popitem
return (key, self.pop(key))
File "/usr/local/lib/python3.4/site-packages/cachetools/abc.py", line 36, in pop
raise KeyError(key)
KeyError: "my_key"