2025-05-31 14:19:00 +00:00

154 lines
4.3 KiB
Python

import os
import sys
import time
import traceback
from contextlib import asynccontextmanager
from pathlib import Path
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from loguru import logger
# Print current directory and Python path for debugging
print(f"Current directory: {os.getcwd()}")
print(f"Python path: {sys.path}")
# Ensure app is in Python path
PROJECT_ROOT = Path(__file__).parent.absolute()
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
print(f"Added {PROJECT_ROOT} to Python path")
try:
from app.api.v1.api import api_router
from app.core.config import settings
from app.core.logging import setup_logging
print("Successfully imported application modules")
except Exception as e:
print(f"Error importing application modules: {e}")
traceback.print_exc()
sys.exit(1)
# Simplified lifespan to prevent startup errors
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Context manager for FastAPI app lifespan events.
Simplified to prevent startup errors.
"""
print("Starting application lifespan...")
# Don't use complex startup logic that might fail
yield
print("Application shutdown...")
# Create the FastAPI application with a simplified configuration
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
version=settings.VERSION,
docs_url="/docs",
redoc_url="/redoc",
)
# Set up basic logging
try:
setup_logging()
logger.info(f"Starting up {settings.PROJECT_NAME}")
except Exception as e:
print(f"Error setting up logging: {e}")
# Continue without logging rather than failing startup
# Simple process time middleware with error handling
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""
Middleware to add X-Process-Time header to response.
Includes error handling.
"""
start_time = time.time()
try:
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
# Log request details (using print as a fallback if logger fails)
try:
logger.info(
f"{request.method} {request.url.path} "
f"Status: {response.status_code} "
f"Process Time: {process_time:.4f}s"
)
except Exception:
print(
f"{request.method} {request.url.path} "
f"Status: {response.status_code} "
f"Process Time: {process_time:.4f}s"
)
return response
except Exception as e:
process_time = time.time() - start_time
print(f"Error processing request {request.url.path}: {e}")
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"},
)
# Simple CORS middleware
try:
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins
allow_credentials=True,
allow_methods=["*"], # Allow all methods
allow_headers=["*"], # Allow all headers
)
print("CORS middleware added")
except Exception as e:
print(f"Error adding CORS middleware: {e}")
# Try to include API router
try:
app.include_router(api_router, prefix=settings.API_V1_STR)
print(f"API router added with prefix: {settings.API_V1_STR}")
except Exception as e:
print(f"Error including API router: {e}")
# Add a fallback router if the main one fails
fallback_router = FastAPI()
app.include_router(fallback_router)
# Basic health check endpoint
@app.get("/health", tags=["health"])
async def health_check():
"""
Health check endpoint to verify the API is running.
"""
try:
logger.debug("Health check endpoint called")
except Exception:
pass
return {"status": "healthy"}
# Simple root endpoint
@app.get("/", tags=["root"])
async def root():
"""
Root endpoint for quick testing.
"""
return {"message": "Manga Inventory API is running"}
if __name__ == "__main__":
# Simplified server startup
print("Starting server with uvicorn...")
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)