Spaces:
Sleeping
Sleeping
| from dotenv import load_dotenv | |
| load_dotenv() | |
| import logging | |
| import os | |
| import uvicorn | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, Request, Response | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import RedirectResponse | |
| from app.api.routers.chat import chat_router | |
| from app.api.routers.user import user_router | |
| from app.settings import init_settings | |
| from app.observability import init_observability | |
| from fastapi.staticfiles import StaticFiles | |
| from alembic.config import Config | |
| from alembic import command | |
| from app.engine.postgresdb import engine, Base, SessionLocal | |
| logger = logging.getLogger("uvicorn") | |
| # Create all tables in the database | |
| Base.metadata.create_all(bind=engine) | |
| def run_migrations(): | |
| alembic_cfg = Config("alembic.ini") | |
| command.upgrade(alembic_cfg, "head") | |
| async def lifespan(app_: FastAPI): | |
| logger.info("Starting up...") | |
| logger.info("Run 'alembic upgrade head' to apply migrations...") | |
| run_migrations() | |
| yield | |
| logger.info("Shutting down...") | |
| app = FastAPI(lifespan=lifespan) | |
| async def db_session_middleware(request: Request, call_next): | |
| response = Response("Internal server error", status_code=500) | |
| try: | |
| request.state.db = SessionLocal() | |
| response = await call_next(request) | |
| finally: | |
| request.state.db.close() | |
| return response | |
| init_settings() | |
| init_observability() | |
| environment = os.getenv("ENVIRONMENT", "dev") # Default to 'development' if not set | |
| if environment == "dev": | |
| logger.warning("Running in development mode - allowing CORS for all origins") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Redirect to documentation page when accessing base URL | |
| async def redirect_to_docs(): | |
| return RedirectResponse(url="/docs") | |
| if os.path.exists("data"): | |
| app.mount("/api/data", StaticFiles(directory="data"), name="static") | |
| app.include_router(chat_router, prefix="/api/chat") | |
| app.include_router(user_router) | |
| if __name__ == "__main__": | |
| app_host = os.getenv("APP_HOST", "0.0.0.0") | |
| app_port = int(os.getenv("APP_PORT", "8000")) | |
| reload = True if environment == "dev" else False | |
| uvicorn.run(app="main:app", host=app_host, port=app_port, reload=reload) | |