Issue
i was messing around with the sqlalchemy ORM functionality
i was able to make it work on my main app but when i created a separate file test.py
to test something, i kept getting event loop closed errors:
Exception ignored in: <function Connection.__del__ at 0x7f7041c07310>
Traceback (most recent call last):
File "/home/krypt/Documents/Projects/app/env/lib/python3.9/site-packages/aiomysql/connection.py", line 1072, in __del__
File "/home/krypt/Documents/Projects/app/env/lib/python3.9/site-packages/aiomysql/connection.py", line 298, in close
File "/usr/lib/python3.9/asyncio/selector_events.py", line 700, in close
File "/usr/lib/python3.9/asyncio/base_events.py", line 746, in call_soon
File "/usr/lib/python3.9/asyncio/base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
here is the code for test.py
:
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.future import select
from sqlalchemy import delete
import asyncio
Base = declarative_base()
class Table(Base):
__tablename__ = 'Table'
id = Column(Integer, primary_key=True)
string = Column(String(30))
prefix = Column(String(1), default = "!")
async def main():
engine = create_async_engine("mariadb+aiomysql://user:[email protected]:3306/dbname")
session = AsyncSession(engine)
stmt = select(Table).where(Table.prefix == "!")
res = await session.execute(stmt)
row = res.scalars().first()
print(row)
asyncio.run(main())
Solution
The problem seems to be that aiomysql is trying to close its connection after the event loop has closed. I could make the code in the question work by ensuring that the session was closed and the engine disposed.
async def main():
engine = create_async_engine("mariadb+aiomysql://user:[email protected]:3306/dbname")
async with AsyncSession(engine) as session:
stmt = select(Table).where(Table.prefix == "!")
res = await session.execute(stmt)
row = res.scalars().first()
print(row)
await engine.dispose()
There's some discussion about this here (towards the end); explicitly closing and disposing is the recommended workaround to prevent the connection's __del__
method executing after the event loop has closed.
Answered By - snakecharmerb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.