|
| 1 | +"""Application implementation - ASGI.""" |
| 2 | + |
| 3 | +from fastapi import FastAPI, Request |
| 4 | +from fastapi.exceptions import RequestValidationError |
| 5 | +from fastapi.responses import JSONResponse |
| 6 | +from loguru import logger |
| 7 | +from fastapi.staticfiles import StaticFiles |
| 8 | + |
| 9 | +from app.config import config |
| 10 | +from app.models.exception import HttpException |
| 11 | +from app.router import root_api_router |
| 12 | +from app.utils import utils |
| 13 | + |
| 14 | + |
| 15 | +def exception_handler(request: Request, e: HttpException): |
| 16 | + return JSONResponse( |
| 17 | + status_code=e.status_code, |
| 18 | + content=utils.get_response(e.status_code, e.data, e.message), |
| 19 | + ) |
| 20 | + |
| 21 | + |
| 22 | +def validation_exception_handler(request: Request, e: RequestValidationError): |
| 23 | + return JSONResponse( |
| 24 | + status_code=400, |
| 25 | + content=utils.get_response(status=400, data=e.errors(), message='field required'), |
| 26 | + ) |
| 27 | + |
| 28 | + |
| 29 | +def get_application() -> FastAPI: |
| 30 | + """Initialize FastAPI application. |
| 31 | +
|
| 32 | + Returns: |
| 33 | + FastAPI: Application object instance. |
| 34 | +
|
| 35 | + """ |
| 36 | + instance = FastAPI( |
| 37 | + title=config.project_name, |
| 38 | + description=config.project_description, |
| 39 | + version=config.project_version, |
| 40 | + debug=False, |
| 41 | + ) |
| 42 | + instance.include_router(root_api_router) |
| 43 | + instance.add_exception_handler(HttpException, exception_handler) |
| 44 | + instance.add_exception_handler(RequestValidationError, validation_exception_handler) |
| 45 | + return instance |
| 46 | + |
| 47 | + |
| 48 | +app = get_application() |
| 49 | +public_dir = utils.public_dir() |
| 50 | +app.mount("/", StaticFiles(directory=public_dir, html=True), name="") |
| 51 | + |
| 52 | + |
| 53 | +@app.on_event("shutdown") |
| 54 | +def shutdown_event(): |
| 55 | + logger.info("shutdown event") |
| 56 | + |
| 57 | + |
| 58 | +@app.on_event("startup") |
| 59 | +def startup_event(): |
| 60 | + logger.info("startup event") |
0 commit comments