Skip to content

Commit

Permalink
feat: use lifespans for more reliable setup/teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
isidentical committed Jan 23, 2024
1 parent b974fdc commit 60b730a
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions projects/fal/src/fal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import inspect
import os
import fal.api
from contextlib import asynccontextmanager
from fal.toolkit import mainify
from fastapi import FastAPI
from typing import Any, NamedTuple, Callable, TypeVar, ClassVar
Expand Down Expand Up @@ -72,14 +73,21 @@ def serve(self) -> None:
import uvicorn

app = self._build_app()
self.setup()
uvicorn.run(app, host="0.0.0.0", port=8080)

def _build_app(self) -> FastAPI:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

_app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI):
self.setup()
try:
yield
finally:
self.teardown()

_app = FastAPI(lifespan=lifespan)

_app.add_middleware(
CORSMiddleware,
Expand Down Expand Up @@ -145,6 +153,9 @@ def order_schema_object(schema: dict[str, Any]):

return spec

def teardown(self):
"""Teardown the application after serving."""


@mainify
def endpoint(path: str) -> Callable[[EndpointT], EndpointT]:
Expand Down

0 comments on commit 60b730a

Please sign in to comment.