Refactor: Relocate bootstrap and validation logic into lifespan context manager
This commit is contained in:
62
app/main.py
62
app/main.py
@@ -1,4 +1,4 @@
|
||||
import datetime, json, os, pytz, random, secrets # , uvicorn
|
||||
import datetime, json, os, pytz, random, secrets, contextlib # , uvicorn
|
||||
|
||||
from enum import Enum
|
||||
#from datetime import datetime, time, timedelta
|
||||
@@ -34,6 +34,40 @@ log = logging.getLogger(__name__)
|
||||
#format='[%(asctime)s] %(levelname)s @ %(module)s.%(funcName)s()#%(lineno)d: %(message)s'
|
||||
#)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""
|
||||
Handles application startup and shutdown lifecycle.
|
||||
"""
|
||||
log.setLevel(logging.INFO)
|
||||
log.info('### **** *** ** * Aether API v4 using FastAPI - Startup Lifespan Initiated * ** *** **** ###')
|
||||
|
||||
# 1. Bootstrapping Configuration from DB with robust error handling
|
||||
log.info("Bootstrapping Configuration...")
|
||||
try:
|
||||
if bootstrap_db_config(config.settings):
|
||||
log.info("Successfully bootstrapped configuration from database.")
|
||||
# Re-initialize the database engine with new credentials/URI
|
||||
if reconnect_db():
|
||||
log.info("Database connection re-established with production configuration.")
|
||||
else:
|
||||
log.warning("FAILED to re-establish database connection after bootstrap. Falling back to .env settings.")
|
||||
else:
|
||||
log.warning("System bootstrap from DB returned no results. Using environment defaults.")
|
||||
except Exception as e:
|
||||
log.error(f"Unexpected error during configuration bootstrap: {e}. Falling back to .env settings.")
|
||||
|
||||
# 2. Final validation of critical infrastructure
|
||||
validate_critical_config(config.settings)
|
||||
|
||||
log.info('### **** *** ** * Aether API v4 using FastAPI - Startup Sequence Complete * ** *** **** ###')
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown logic
|
||||
log.info('### **** *** ** * Aether API v4 using FastAPI - Shutdown Lifespan Initiated * ** *** **** ###')
|
||||
log.info('The Aether FastAPI API is shutting down...')
|
||||
|
||||
|
||||
print('### **** *** ** * Aether API v4 using FastAPI - About to try FastAPI() while loading... * ** *** **** ###')
|
||||
app = FastAPI(
|
||||
@@ -42,34 +76,10 @@ app = FastAPI(
|
||||
description = 'One Sky IT\'s Aether API v4 using FastAPI.',
|
||||
version = '4.9.0',
|
||||
operationsSorter = 'method',
|
||||
lifespan = lifespan,
|
||||
)
|
||||
|
||||
|
||||
log.setLevel(logging.INFO)
|
||||
# log.debug(config.settings)
|
||||
|
||||
print('### **** *** ** * Aether API v4 using FastAPI - Bootstrapping Configuration... * ** *** **** ###')
|
||||
|
||||
# Sync settings from DB with robust error handling
|
||||
try:
|
||||
if bootstrap_db_config(config.settings):
|
||||
log.info("Successfully bootstrapped configuration from database.")
|
||||
# Re-initialize the database engine with new credentials/URI
|
||||
if reconnect_db():
|
||||
log.info("Database connection re-established with production configuration.")
|
||||
else:
|
||||
log.warning("FAILED to re-establish database connection after bootstrap. Falling back to .env settings.")
|
||||
else:
|
||||
log.warning("System bootstrap from DB returned no results. Using environment defaults.")
|
||||
except Exception as e:
|
||||
log.error(f"Unexpected error during configuration bootstrap: {e}. Falling back to .env settings.")
|
||||
|
||||
# Perform final validation of critical infrastructure
|
||||
validate_critical_config(config.settings)
|
||||
|
||||
print('### **** *** ** * Aether API v4 using FastAPI - Finished Configuration Phase * ** *** **** ###' )
|
||||
log.debug(config.settings)
|
||||
|
||||
# @lru_cache()
|
||||
# def get_settings():
|
||||
# return config.Settings()
|
||||
|
||||
Reference in New Issue
Block a user