From 4567ab12f868a87447f2b53c6931c1707ef3759d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Thu, 27 Oct 2022 23:48:02 +0000 Subject: [PATCH] app middlewares --- api/advent22_api/app.py | 30 ++++++++++++++++++++++++++++++ api/advent22_api/settings.py | 1 + 2 files changed, 31 insertions(+) diff --git a/api/advent22_api/app.py b/api/advent22_api/app.py index c600709..b0fcc78 100644 --- a/api/advent22_api/app.py +++ b/api/advent22_api/app.py @@ -1,4 +1,6 @@ from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles from .routers import router from .settings import SETTINGS @@ -19,4 +21,32 @@ app = FastAPI( redoc_url=SETTINGS.redoc_url, ) + +@app.on_event("startup") +async def add_middlewares() -> None: + if SETTINGS.production_mode: + # Mount frontend in production mode + app.mount( + path="/", + app=StaticFiles( + directory=SETTINGS.ui_directory, + html=True, + ), + name="frontend", + ) + + else: + # Allow CORS in debug mode + app.add_middleware( + CORSMiddleware, + allow_origins=[ + "*", + ], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + expose_headers=["*"], + ) + + app.include_router(router) diff --git a/api/advent22_api/settings.py b/api/advent22_api/settings.py index f93e414..644a662 100644 --- a/api/advent22_api/settings.py +++ b/api/advent22_api/settings.py @@ -35,6 +35,7 @@ class Settings(BaseSettings): ##### production_mode: bool = False + ui_directory: str = "/html" ##### # openapi settings