ADD logger lifespan init deps&errors

main
Сергей Ванюшкин 2024-08-16 12:21:14 +00:00
parent 2baacbf50f
commit 8f2db50067
14 changed files with 80 additions and 30 deletions

View File

@ -1,10 +1,15 @@
import uvicorn import uvicorn
if __name__ == "__main__":
def main():
uvicorn.run( uvicorn.run(
"fastfood_two.main:app_factory", "fastfood_two.entrypoint.main:app_factory",
host="0.0.0.0", host="0.0.0.0",
port=8000, port=8000,
factory=True, factory=True,
reload=True, reload=True,
) )
if __name__ == "__main__":
main()

View File

@ -1,7 +1,9 @@
import logging import logging
def logger_configure(level=logging.INFO) -> None: def configure_logger(level=logging.INFO) -> None:
"""Configure the logger output string."""
logging.basicConfig( logging.basicConfig(
level=level, level=level,
datefmt="%Y-%m-%d %H:%M:%S", datefmt="%Y-%m-%d %H:%M:%S",

View File

View File

@ -0,0 +1,14 @@
import logging
from fastapi import FastAPI
from fastfood_two.common.logger import configure_logger
logger = logging.getLogger(__name__)
configure_logger(level=logging.INFO)
def init_dependencies(app: FastAPI) -> None:
"""Initialize FastAPI dependencies."""
logger.info("Dependencies initialized")

View File

@ -0,0 +1,6 @@
from fastapi import FastAPI
def init_errorhandlers(app: FastAPI) -> None:
"""Initialize FastAPI error handlers."""
pass

View File

@ -0,0 +1,50 @@
import logging
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from fastapi import FastAPI
from fastfood_two.common.logger import configure_logger
from fastfood_two.entrypoint.dependencies import init_dependencies
from fastfood_two.entrypoint.error_handlers import init_errorhandlers
logger = logging.getLogger(__name__)
configure_logger(level=logging.INFO)
@asynccontextmanager
async def app_lifespan(app: FastAPI) -> AsyncGenerator:
"""Application lifespan.
This function is called when the application starts and stops.
Do not use this method directly, use the FastAPI `lifespan` instead.
:param app: FastAPI application
:type app: FastAPI
"""
logger.info("Application lifespan started")
init_dependencies(app)
init_errorhandlers(app)
yield
logger.info("Application lifespan stopped")
def app_factory() -> FastAPI:
"""Create a FastAPI application.
Create a FastAPI application and initialize all dependencies.
:return: FastAPI
:rtype: FastAPI
"""
app = FastAPI(
lifespan=app_lifespan,
)
return app

View File

@ -1,27 +0,0 @@
import logging
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from fastapi import FastAPI
from fastfood_two.common.logger import logger_configure
logger = logging.getLogger(__name__)
@asynccontextmanager
async def app_lifespan(app: FastAPI) -> AsyncGenerator:
"""Application lifespan."""
logger_configure(level=logging.INFO)
logger.info("Application started")
yield
logger.info("Application stopped")
def app_factory() -> FastAPI:
"""Create a FastAPI application."""
app = FastAPI(
lifespan=app_lifespan,
)
return app