Issue trying to use SQLModel with AsyncSession and object conversion from Row #1472
-
First Check
Commit to Help
Example Codefrom sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Field, SQLModel
from typing import Optional
user = "user"
password = "password"
host = "db"
db = "db"
engine = create_async_engine(f"mysql+aiomysql://{user}:{password}@{host}/{db}")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)
async def get_db():
async with SessionLocal() as session:
yield session
class Item(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
title: str = Field()
content: str = Field()
## Endpoint for delete
from fastapi import FastAPI, Depends
from sqlalchemy import select, update
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.orm import selectinload
from database import Item, get_db
import logging
app = FastAPI()
async def get_item(item_id: int, db: AsyncSession):
query = select(Item).where(Item.id == item_id).options(selectinload('*'))
result = await db.exec(query)
return result.first()
@app.delete("item/{item_id}")
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
await db.delete(await get_item(item_id, db))
await db.commit()
return await get_all(db) DescriptionI'm trying to do some really silly implementation of a CRUD but I am not able to make it work using an Async Connection to the MySQL Database, the error I get is that the object is not being converted to a SQLModel but that it stays as a Row. It's the following:
Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.6 Python Version3.9.9 Additional ContextI think what is happening is that the async connection is not set-up properly connected to the SQLModel implementation so it can get automatically converted to the SQLModel object but I'm not sure which should be the expected process. Please let me know if you need more information about it |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
Is it an error that occurred after attempting to create a table? |
Beta Was this translation helpful? Give feedback.
-
No, when trying to delete the resource given that the This is the exact line where it fails:
|
Beta Was this translation helpful? Give feedback.
This comment has been hidden.
This comment has been hidden.
-
Why is this difference only specific to the async style? Is there any place where I could find it documented to avoid it in the future? |
Beta Was this translation helpful? Give feedback.
This comment has been hidden.
This comment has been hidden.
-
You just need to import from typing import Optional
from fastapi import Depends, FastAPI
from sqlalchemy import StaticPool
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import selectinload, sessionmaker
from sqlmodel import Field, SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
engine = create_async_engine(
"sqlite+aiosqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)
async def get_db():
async with SessionLocal() as session:
yield session
class Item(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
title: str = Field()
content: str = Field()
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
session: AsyncSession
async with SessionLocal() as session:
session.add(Item(title="123", content="456"))
await session.commit()
yield
app = FastAPI(lifespan=lifespan)
async def get_item(item_id: int, db: AsyncSession):
query = select(Item).where(Item.id == item_id).options(selectinload('*'))
result = await db.exec(query)
return result.first()
@app.delete("/item/{item_id}")
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
await db.delete(await get_item(item_id, db))
await db.commit()
return "ok" |
Beta Was this translation helpful? Give feedback.
You just need to import
select
fromSQLModel
instead ofsqlalchemy
: