prod-wag-backend-automate-s.../ApiDefaults/create_app.py

64 lines
2.1 KiB
Python

from ApiControllers.abstracts.event_clusters import RouterCluster, EventCluster
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
def create_events_if_any_cluster_set():
import Events
if not Events.__all__:
return
router_cluster_stack: list[RouterCluster] = [
getattr(Events, e, None) for e in Events.__all__
]
for router_cluster in router_cluster_stack:
event_cluster_stack: list[EventCluster] = list(
router_cluster.event_clusters.values()
)
for event_cluster in event_cluster_stack:
print(f"Creating event:", event_cluster.name)
try:
event_cluster.set_events_to_database()
except Exception as e:
print(f"Error creating event cluster: {e}")
def create_app():
from ApiDefaults.open_api_creator import create_openapi_schema
from ApiDefaults.config import api_config
from ApiControllers.middlewares.token_middleware import token_middleware
from ApiControllers.initializer.create_route import RouteRegisterController
from Endpoints.routes import get_routes
application = FastAPI(**api_config.api_info)
# application.mount(
# "/application/static",
# StaticFiles(directory="application/static"),
# name="static",
# )
application.add_middleware(
CORSMiddleware,
allow_origins=api_config.ALLOW_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@application.middleware("http")
async def add_token_middleware(request: Request, call_next):
return await token_middleware(request, call_next)
@application.get("/", description="Redirect Route", include_in_schema=False)
async def redirect_to_docs():
return RedirectResponse(url="/docs")
route_register = RouteRegisterController(app=application, router_list=get_routes())
application = route_register.register_routes()
create_events_if_any_cluster_set()
application.openapi = lambda _=application: create_openapi_schema(_)
return application