Skip to content

Commit

Permalink
wrap lifespan decorator in docs and add missing type (#1362)
Browse files Browse the repository at this point in the history
Co-authored-by: collerek <[email protected]>
  • Loading branch information
inktrap and collerek authored Dec 4, 2024
1 parent aa82051 commit 6be6136
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions docs/fastapi/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Here you can find a very simple sample application code.
Define startup and shutdown procedures using FastAPI lifespan and use is in the
application.
```python
from typing import List, Optional
from typing import List, Optional, AsyncIterator

import databases
import sqlalchemy
Expand All @@ -41,22 +41,24 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI


@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.database.is_connected:
await config.database.connect()
def get_lifespan(config):
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.database.is_connected:
await config.database.connect()

yield

if config.database.is_connected:
await config.database.disconnect()
yield

if config.database.is_connected:
await config.database.disconnect()
return lifespan

base_ormar_config = ormar.OrmarConfig(
metadata=sqlalchemy.MetaData(),
database=databases.Database("sqlite:///test.db"),
)
app = FastAPI(lifespan=lifespan(base_ormar_config))

app = FastAPI(lifespan=get_lifespan(base_ormar_config))
```

!!!info
Expand Down

0 comments on commit 6be6136

Please sign in to comment.