python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

support startup/shutdown events using an async contextmanager

Open graingert opened this issue 1 year ago • 1 comments

eg, I'd like to be able to run background tasks and pool http connections:

@contextlib.asynccontextmanager
async def lifespan_context():
    async with anyio.create_task_group() as tg, httpx.AsyncClient() as client:
        yield {"tg": tg, "client": client}

app = Server("name", lifespan_context=lifespan_context)

anything yielded from the context manager should be available on app.request_context.state

graingert avatar Nov 25 '24 19:11 graingert

Thank you for the suggestion. I think that makes a lot of sense. Since FastAPI (and I assume others) do the same, it probably is the right pattern. I'll self-assign and see that I get to implement this. Of course we also accept PRs.

dsp-ant avatar Nov 25 '24 20:11 dsp-ant

This is implemented in v1.3.0

dsp-ant avatar Feb 21 '25 10:02 dsp-ant