Reputation: 451
Trying to use event listeners(https://docs.sqlalchemy.org/en/14/core/events.html#sqlalchemy.events.ConnectionEvents
) on a async sqlalchemy engine and am getting this error:
{NotImplementedError}asynchronous events are not implemented at this time. Apply synchronous listeners to the AsyncEngine.sync_engine or AsyncConnection.sync_connection attributes.
If I'm understanding this correctly I cant use events on an async engine and I have to switch to a sync engine if I want event support?
engine: Engine = create_async_engine(
URL, echo=True, future=True
)
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False, future=True
)
event.listens_for(engine, "do_connect")(do_connect_listener)
event.listens_for(engine, "engine_connect")(engine_connect_listener)
Upvotes: 6
Views: 5012
Reputation: 451
got an answer from the SQLAlchemy discussion section on github. All credit to the OP(https://github.com/sqlalchemy/sqlalchemy/discussions/6594#discussioncomment-836437):
"Hi,
As suggested by the exception you may use the sync_engine/sync_connection when applying events. Here is an example:"
import asyncio
from sqlalchemy import event
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
@event.listens_for(engine.sync_engine, "do_connect")
def do_connect(dialect, conn_rec, cargs, cparams):
print("some-function")
@event.listens_for(engine.sync_engine, "engine_connect")
def engine_connect(conn, branch):
print("engine_connect", conn.exec_driver_sql("select 1").scalar())
async def go():
async with engine.connect() as conn:
res = await conn.exec_driver_sql("select 2")
print("go", res.scalar())
asyncio.run(go())
Upvotes: 9