Skip to content
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

Added Documentation for usage with async tools. Fixes #626 #633

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

deshetti
Copy link

@deshetti deshetti commented Aug 8, 2023

I have spent a good amount of time to figure out async implementation with SQLModel & FastAPI in one of our projects and thought this would be a helpful guide for anyone who is looking to do the same in their projects.

A simple working project is available here to test. Running the docker-compose will start the postgres with the required database: https://github.com/deshetti/sqlmodel-async-example

@github-actions
Copy link

github-actions bot commented Aug 8, 2023

📝 Docs preview for commit a5fe1d1 at: https://ececea1e.sqlmodel.pages.dev

@github-actions
Copy link

github-actions bot commented Aug 9, 2023

📝 Docs preview for commit b0081f5 at: https://049f644f.sqlmodel.pages.dev

@tiangolo tiangolo added the docs Improvements or additions to documentation label Oct 22, 2023
```

## Final code
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
```python

Comment on lines +15 to +17
```
pip install sqlmodel asyncpg fastapi uvicorn
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
pip install sqlmodel asyncpg fastapi uvicorn
```
```bash
pip install sqlmodel asyncpg fastapi uvicorn

)


# Ayschronous Context manager for handling database sessions

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# Ayschronous Context manager for handling database sessions
# Asynchronous Context manager for handling database sessions

@StashOfCode
Copy link

StashOfCode commented Feb 8, 2024

@tiangolo , are you merging this in this century or next?

@moralespanitz
Copy link

@tiangolo Why don't you add the contribution?

@vduseev
Copy link

vduseev commented Jul 11, 2024

Interesting approach. Why not use async_sessionmaker?

@Lexachoc
Copy link

Lexachoc commented Jul 11, 2024

The async session part doesn't work for me and gives an error when executing statement.

https://github.com/deshetti/sqlmodel-async-example/blob/e412da00f557a352ee3f66a8545ef11401ea5dde/main.py#L42-L47

# Ayschronous Context manager for handling database sessions
@asynccontextmanager
async def get_session() -> AsyncSession:
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with async_session() as session:
        yield session

error occurs at:
results= await session.exec(statement)

within an endpoint where the session is a dependency: session: AsyncSession = Depends(get_session)

error message: '_AsyncGeneratorContextManager' object has no attribute 'exec'

Also, there is a warning in Pycharm that says:
Unexpected type(s): (Any, Type[AsyncSession], bool) Possible type(s): (Connection | Connection | Engine | Engine | None, None, bool) (Connection | Connection | Engine | Engine | AsyncConnection | AsyncConnection | AsyncEngine | AsyncEngine | None, Type[_TSessionMakerType], bool) (Connection | Connection | Engine | Engine | None, None, bool) (Connection | Connection | Engine | Engine | None, Type[_TSessionMakerType], bool)
for the sessionmaker

To overcome this, I use directly the AsyncSession instead of sessionmaker:

async def get_session() -> AsyncSession:
    async with AsyncSession(data_engine) as session:
        yield session

which works for me when using the async session as dependencies.

Hope this helps others or do you have an idea why the original solution doesn't work?

This seems to be the reason for the error or is related to it: fastapi/fastapi#9054 (comment)

version:
FastAPI: 0.111.0
sqlmodel: 0.0.19
But this already happens with older versions, even if I use the latest version.

# Endpoint to create a new user
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.dict() is deprecated for model_dump()

Suggested change
db_user = User(**user.dict())
db_user = User(**user.model_dump())

```python
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.dict() is deprecated for model_dump()

Suggested change
db_user = User(**user.dict())
db_user = User(**user.model_dump())

Comment on lines +88 to +92
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())
result = await create_user(db_user)
return result

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe drop the create_user() function and just have everything in here. We also get the added benefit of showing of dependency injection, we are in the advanced section after all.

Suggested change
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())
result = await create_user(db_user)
return result
@app.post("/users/", response_model=User)
async def create_user_endpoint(
user: UserCreate,
session: AsyncSession = Depends(get_session),
):
db_user = User(user.model_dump())
session.add(db_user)
await session.commit()
await session.refresh(db_user)
return db_user

@zuoc1993
Copy link

zuoc1993 commented Dec 5, 2024

When will this be released?


from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can use

class AsyncSession(_AsyncSession):
instead of SQLAlchemy's

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.