New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add documentation about how to use the async tools (session, etc) #626
Comments
First of all we have to import from sqlalchemy which I dont like. It is a bit confusing. Hence I would like to import it from sqlmodel itself. Like how we have with Session(engine) as session:
session.exec() we should have async with AsyncSession(engine) as session:
await session.exec() so it becomes easier for us to make sessions. |
from collections.abc import AsyncGenerator
from typing import Annotated, Callable
from fastapi import Depends
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, Session
from core.config import settings
##############
# region 'Async Session'
engine = create_async_engine(
settings.SQLALCHEMY_DATABASE_URI_ASYNC,
future=True,
echo=settings.LOCAL_DEV,
hide_parameters=not settings.LOCAL_DEV,
connect_args={
# https://www.postgresql.org/docs/current/runtime-config.html
"server_settings": {
"application_name": f"{settings.PROJECT_NAME} {settings.VERSION} async",
"jit": "off",
},
},
)
AsyncSessionFactory = sessionmaker(
bind=engine,
autoflush=False,
expire_on_commit=False,
class_=AsyncSession,
)
async def get_db() -> AsyncGenerator:
yield AsyncSessionFactory
Session = Annotated[AsyncSession, Depends(get_db)]
# endregion
##############
@router.post(...)
async def some_function(
session: Session)
async with session() as db: # noqa
...
stmt = select(Model1)
items = await db.execute(stmt)
data = items.all()
return data asyncpg, works fine, except:
|
A full working example of the following is here: https://github.com/deshetti/sqlmodel-async-example
|
@tiangolo Can I work on this? Add a sqlmodel version of asyncsession as well as create_async_engine |
It looks like sqlmodel has already implemented its own asyncsession but is just not importable from the root directory. Currently I believe you need to import it through If we want to adhere to sqlalchemy model import structure it should be However, according to @alvynabranches the proposed solution is @tiangolo what do you think? |
Privileged issue
Issue Content
Add documentation about how to use the async tools (session, etc).
Funding
The text was updated successfully, but these errors were encountered: