Skip to content

Commit

Permalink
App uses lifespan context manager for startup + shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
padraic-shafer committed Mar 4, 2024
1 parent acfa2a2 commit 213790c
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions tiled/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import secrets
import sys
import urllib.parse
from contextlib import asynccontextmanager
from functools import lru_cache, partial
from pathlib import Path
from typing import List
Expand Down Expand Up @@ -195,7 +196,14 @@ def build_app(
)
# If we reach here, the no configuration problems were found.

app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI):
"Manage lifespan events for each event loop that the app runs in"
await startup_event()
yield
await shutdown_event()

app = FastAPI(lifespan=lifespan)

if SHARE_TILED_PATH:
# If the distribution includes static assets, serve UI routes.
Expand Down Expand Up @@ -465,7 +473,6 @@ def override_get_settings():
settings.database_uri = settings.database_uri or "sqlite+aiosqlite://"
return settings

@app.on_event("startup")
async def startup_event():
# Validate the single-user API key.
settings = app.dependency_overrides[get_settings]()
Expand Down Expand Up @@ -668,7 +675,6 @@ async def purge_expired_sessions_and_api_keys():
asyncio.create_task(purge_expired_sessions_and_api_keys())
)

@app.on_event("shutdown")
async def shutdown_event():
# Run shutdown tasks collected from trees (adapters).
for task in tasks.get("shutdown", []):
Expand Down

0 comments on commit 213790c

Please sign in to comment.