Where SQLAlchemy async API meets multithreading.
The problem:
got Future attached to a different loop.
The solutions:
- Bad
from sqlalchemy.pool import NullPool
create_async_engine(
url=database_uri,
poolclass=NullPool,
)
-
Remove
metaclass=SingletonHash
fromBaseOrm
and create engine along with every database transaction, then dispose it. Also Bad. -
At each streamlit page, ensure that the same asyncio loop is used during the user session. Nice!
if "loop" not in st.session_state:
st.session_state["loop"] = asyncio.new_event_loop()
loop = st.session_state["loop"]
loop.run_until_complete(main())