Skip to content

Instantly share code, notes, and snippets.

@mrmamongo
Created October 23, 2023 13:48
Show Gist options
  • Save mrmamongo/091f415aaeed112eb8f034a39f0e390f to your computer and use it in GitHub Desktop.
Save mrmamongo/091f415aaeed112eb8f034a39f0e390f to your computer and use it in GitHub Desktop.
logger = logging.getLogger(__name__)
class Application:
def __init__(
self,
config: Config,
app: FastAPI
) -> None:
self.config = config
self.app = app
@classmethod
async def from_config(cls, config: Config) -> Application: # a.k.a startup
setup_logging(config)
logger.info("Initializing FastAPI application")
fastapi_app = FastAPI()
logger.info("Initializing middlewares")
# Add CORS middleware
fastapi_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
logger.info("Initializing exeception handlers")
# TODO: реализовать обработку исключений
logger.info("Creating application")
application = Application(
config=config,
app=fastapi_app,
listener=factory.listener(commandapi_app),
sender_proxy=factory.sender_proxy(),
)
logger.info("Initializing application finished")
return application
async def start(self) -> None:
logger.info("HTTP server is starting")
try:
server = uvicorn.Server(
config=uvicorn.Config(
app=self.app,
host="0.0.0.0",
port=int(self.config.API_PORT),
)
)
await server.serve()
except asyncio.CancelledError:
logger.info("HTTP server has been interrupted")
except BaseException as unexpected_error:
logger.exception("HTTP server failed to start")
raise StartServerException from unexpected_error
async def dispose(self) -> None:
logger.info("Application is shutting down...")
dispose_errors: list[str] = []
# TODO: закрыть все соединения\освободить все ресурсы
if len(dispose_errors) != 0:
logger.error("Application has shut down with errors")
raise DisposeException(
"Application has shut down with errors, see logs above"
)
logger.info("Application has successfully shut down")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment