| 1 | """Application implementation - ASGI.""" |
| 2 | |
| 3 | import os |
| 4 | |
| 5 | from fastapi import FastAPI, Request |
| 6 | from fastapi.exceptions import RequestValidationError |
| 7 | from fastapi.middleware.cors import CORSMiddleware |
| 8 | from fastapi.responses import JSONResponse |
| 9 | from fastapi.staticfiles import StaticFiles |
| 10 | from loguru import logger |
| 11 | |
| 12 | from app.config import config |
| 13 | from app.models.exception import HttpException |
| 14 | from app.router import root_api_router |
| 15 | from app.utils import utils |
| 16 | |
| 17 | |
| 18 | def exception_handler(request: Request, e: HttpException): |
| 19 | return JSONResponse( |
| 20 | status_code=e.status_code, |
| 21 | content=utils.get_response(e.status_code, e.data, e.message), |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | def validation_exception_handler(request: Request, e: RequestValidationError): |
| 26 | return JSONResponse( |
| 27 | status_code=400, |
| 28 | content=utils.get_response( |
| 29 | status=400, data=e.errors(), message="field required" |
| 30 | ), |
| 31 | ) |
| 32 | |
| 33 | |
| 34 | def get_application() -> FastAPI: |
| 35 | """Initialize FastAPI application. |
| 36 | |
| 37 | Returns: |
| 38 | FastAPI: Application object instance. |
| 39 | |
| 40 | """ |
| 41 | instance = FastAPI( |
| 42 | title=config.project_name, |
| 43 | description=config.project_description, |
| 44 | version=config.project_version, |
| 45 | debug=False, |
| 46 | ) |
| 47 | instance.include_router(root_api_router) |
| 48 | instance.add_exception_handler(HttpException, exception_handler) |
| 49 | instance.add_exception_handler(RequestValidationError, validation_exception_handler) |
| 50 | return instance |
| 51 | |
| 52 | |
| 53 | app = get_application() |
| 54 | |
| 55 | # Configures the CORS middleware for the FastAPI app |
| 56 | cors_allowed_origins_str = os.getenv("CORS_ALLOWED_ORIGINS", "") |
| 57 | origins = cors_allowed_origins_str.split(",") if cors_allowed_origins_str else ["*"] |
| 58 | app.add_middleware( |
| 59 | CORSMiddleware, |
| 60 | allow_origins=origins, |
| 61 | allow_credentials=True, |
| 62 | allow_methods=["*"], |
| 63 | allow_headers=["*"], |
| 64 | ) |
| 65 | |
| 66 | task_dir = utils.task_dir() |
| 67 | app.mount( |
| 68 | "/tasks", StaticFiles(directory=task_dir, html=True, follow_symlink=True), name="" |
| 69 | ) |
| 70 | |
| 71 | public_dir = utils.public_dir() |
| 72 | app.mount("/", StaticFiles(directory=public_dir, html=True), name="") |
| 73 | |
| 74 | |
| 75 | @app.on_event("shutdown") |
| 76 | def shutdown_event(): |
| 77 | logger.info("shutdown event") |
| 78 | |
| 79 | |
| 80 | @app.on_event("startup") |
| 81 | def startup_event(): |
| 82 | logger.info("startup event") |
| 83 |