Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App uses lifespan context manager for startup + shutdown #676

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading