109 lines
2.5 KiB
Python
109 lines
2.5 KiB
Python
"""
|
|
FastAPI Application Entry Point
|
|
Integrated API Gateway + Telegram Bot
|
|
"""
|
|
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from app.core.config import get_settings
|
|
from app.db.database import engine, Base, get_db
|
|
from app.security.middleware import add_security_middleware
|
|
from app.api import transactions, auth
|
|
import redis
|
|
|
|
# Configure logging
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Get settings
|
|
settings = get_settings()
|
|
|
|
# Redis client
|
|
redis_client = redis.from_url(settings.redis_url)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""
|
|
Startup/Shutdown events
|
|
"""
|
|
# === STARTUP ===
|
|
logger.info("🚀 Application starting...")
|
|
|
|
# Create database tables (if not exist)
|
|
Base.metadata.create_all(bind=engine)
|
|
logger.info("✅ Database initialized")
|
|
|
|
# Verify Redis connection
|
|
try:
|
|
redis_client.ping()
|
|
logger.info("✅ Redis connected")
|
|
except Exception as e:
|
|
logger.error(f"❌ Redis connection failed: {e}")
|
|
|
|
yield
|
|
|
|
# === SHUTDOWN ===
|
|
logger.info("🛑 Application shutting down...")
|
|
redis_client.close()
|
|
logger.info("✅ Cleanup complete")
|
|
|
|
|
|
# Create FastAPI application
|
|
app = FastAPI(
|
|
title="Finance Bot API",
|
|
description="API-First Zero-Trust Architecture for Family Finance Management",
|
|
version="1.0.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# Add CORS middleware
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_allowed_origins,
|
|
allow_credentials=settings.cors_allow_credentials,
|
|
allow_methods=settings.cors_allow_methods,
|
|
allow_headers=settings.cors_allow_headers,
|
|
)
|
|
|
|
# Add security middleware
|
|
add_security_middleware(app, redis_client, next(get_db()))
|
|
|
|
# Include API routers
|
|
app.include_router(auth.router)
|
|
app.include_router(transactions.router)
|
|
|
|
|
|
# ========== Health Check ==========
|
|
@app.get("/health", tags=["health"])
|
|
async def health_check():
|
|
"""
|
|
Health check endpoint.
|
|
No authentication required.
|
|
"""
|
|
return {
|
|
"status": "ok",
|
|
"environment": settings.app_env,
|
|
"version": "1.0.0",
|
|
}
|
|
|
|
|
|
# ========== Graceful Shutdown ==========
|
|
import signal
|
|
import asyncio
|
|
|
|
async def shutdown_handler(sig):
|
|
"""Handle graceful shutdown"""
|
|
logger.info(f"Received signal {sig}, shutting down...")
|
|
|
|
# Close connections
|
|
redis_client.close()
|
|
|
|
# Exit
|
|
return 0
|