Source: https://gres.monicz.dev/guide/applications/

# Web apps and testing

Open one `Pool` per process on startup, close it on shutdown, and type query helpers against [`Executor`](https://gres.monicz.dev/api/queries/#gres.Executor) so they run on a pool, checked-out connection, or transaction.

## ASGI lifespan

Open the pool inside the application [lifespan](https://starlette.dev/lifespan/) so it binds to the server's event loop and closes cleanly on exit:

```python
# Partial: requires FastAPI. Starlette and Litestar accept the same
# lifespan function.
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Request
from gres import Executor, Pool


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    async with Pool(max_size=20) as pool:
        app.state.pool = pool
        yield


app = FastAPI(lifespan=lifespan)


def database(request: Request) -> Pool:
    return request.app.state.pool


async def find_station(db: Executor, station: int) -> dict[str, object] | None:
    return await db.fetch_optional(
        'SELECT id, name FROM station WHERE id = $1', (station,)
    )


@app.get('/stations/{station}')
async def get_station(
    station: int, pool: Annotated[Pool, Depends(database)]
) -> dict[str, object]:
    row = await find_station(pool, station)
    if row is None:
        raise HTTPException(status_code=404, detail='Station not found')
    return row


@app.post('/stations/{station}/rename')
async def rename_station(
    station: int, name: str, pool: Annotated[Pool, Depends(database)]
) -> None:
    async with pool.transaction() as tx:
        await tx.execute(
            'UPDATE station SET name = $1 WHERE id = $2', (name, station)
        )
        await tx.execute("SELECT pg_notify('stations', $1)", (str(station),))
```

Single queries can run directly on `pool`. Open `pool.transaction()` inside the handler or service function so commit failures raise before a response is sent. Demand beyond `max_size + max_waiters` raises `PoolBusyError`, which maps cleanly to HTTP 503.

## Testing with pytest-asyncio

With [pytest-asyncio](https://pytest-asyncio.readthedocs.io/), share one session-scoped pool and wrap each test in a transaction that rolls back on teardown:

```toml
# Configuration: pyproject.toml. Fixtures and tests share the session
# event loop that owns the pool.
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "session"
asyncio_default_test_loop_scope = "session"
```

```python
# Partial: conftest.py and a test module. PGHOST, PGDATABASE, and the
# other PG* variables select a test database.
from collections.abc import AsyncIterator

import pytest_asyncio
from gres import Pool, Transaction, scalar


@pytest_asyncio.fixture(scope='session')
async def pool() -> AsyncIterator[Pool]:
    async with Pool() as pool:
        yield pool


@pytest_asyncio.fixture
async def db(pool: Pool) -> AsyncIterator[Transaction]:
    async with pool.transaction() as tx:
        yield tx
        await tx.rollback()


async def test_rename(db: Transaction) -> None:
    await db.execute("INSERT INTO station VALUES (1, 'Harbour')")
    await db.execute("UPDATE station SET name = 'Port' WHERE id = 1")
    assert (
        await db.fetch_one(
            'SELECT name FROM station WHERE id = 1', row=scalar(str)
        )
        == 'Port'
    )
```

Code taking an `Executor` runs inside `db`; nested `transaction()` calls become savepoints and roll back with the fixture. Tests needing a separate session (such as `LISTEN`) should use `pool` directly and clean up their own tables (or isolate databases per worker). Both pytest-asyncio loop-scope settings must match the pool fixture's scope because connections are bound to their opening event loop.
