Skip to content

Commit

Permalink
Migrate to FastAPI lifespan
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathansick committed Dec 19, 2023
1 parent 10141d5 commit 3ad5c04
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/noteburst/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
"""

import json
from contextlib import asynccontextmanager
from importlib.metadata import version
from pathlib import Path
from typing import AsyncIterator

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
Expand All @@ -33,6 +35,20 @@
)
configure_uvicorn_logging(config.log_level)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# Start up event
await arq_dependency.initialize(
mode=config.arq_mode, redis_settings=config.arq_redis_settings
)

yield

# Shut down event
await http_client_dependency.aclose()


app = FastAPI(
title=config.name,
description=Path(__file__).parent.joinpath("description.md").read_text(),
Expand All @@ -41,6 +57,7 @@
docs_url=f"{config.path_prefix}/docs",
redoc_url=f"{config.path_prefix}/redoc",
openapi_tags=[{"name": "v1", "description": "Noteburst v1 REST API"}],
lifespan=lifespan,
)
"""The FastAPI application for noteburst."""

Expand All @@ -54,18 +71,6 @@
app.add_middleware(XForwardedMiddleware)


@app.on_event("startup")
async def startup_event() -> None:
await arq_dependency.initialize(
mode=config.arq_mode, redis_settings=config.arq_redis_settings
)


@app.on_event("shutdown")
async def shutdown_event() -> None:
await http_client_dependency.aclose()


def create_openapi() -> str:
"""Create the OpenAPI spec for static documentation."""
spec = get_openapi(
Expand Down

0 comments on commit 3ad5c04

Please sign in to comment.