Skip to content

Commit

Permalink
Remove deprecated FastAPI events
Browse files Browse the repository at this point in the history
FastAPI's startup and shutdown events have been deprecated and replaced with a single 'lifespan' context manager.
  • Loading branch information
dhirving committed Mar 4, 2024
1 parent ef5a02c commit c33f50c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 18 deletions.
23 changes: 12 additions & 11 deletions src/exposurelog/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

import fastapi
import fastapi.responses
import starlette.requests
Expand All @@ -14,7 +17,15 @@
get_message,
)

app = fastapi.FastAPI()

@asynccontextmanager
async def lifespan(app: fastapi.FastAPI) -> AsyncIterator[None]:
await shared_state.create_shared_state()
yield
await shared_state.delete_shared_state()


app = fastapi.FastAPI(lifespan=lifespan)

subapp = fastapi.FastAPI(
title="Exposure log service",
Expand Down Expand Up @@ -52,13 +63,3 @@ async def root(request: starlette.requests.Request) -> str:
but harder to read.
</html>
"""


@app.on_event("startup")
async def startup_event() -> None:
await shared_state.create_shared_state()


@app.on_event("shutdown")
async def shutdown_event() -> None:
await shared_state.delete_shared_state()
9 changes: 2 additions & 7 deletions src/exposurelog/testutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,19 +88,14 @@ async def create_test_client(
**db_config,
):
# Note: httpx.AsyncClient does not trigger startup and shutdown
# events. We could use asgi-lifespan's LifespanManager,
# but it does not trigger the shutdown event if there is
# an exception, so it does not seem worth the bother.
# events, so we have to manually trigger the lifespan events.
assert not shared_state.has_shared_state()
await main.startup_event()
try:
async with main.lifespan(main.app):
async with httpx.AsyncClient(
app=main.app, base_url="http://test"
) as client:
assert shared_state.has_shared_state()
yield client, messages
finally:
await main.shutdown_event()


@contextlib.contextmanager
Expand Down

0 comments on commit c33f50c

Please sign in to comment.