Fix FastAPI middleware import error for deployment

- Removed custom BaseHTTPMiddleware that was causing import errors
- Simplified CORS configuration to use only standard FastAPI CORSMiddleware
- Kept explicit OPTIONS handler for maximum compatibility
- Fixed compatibility issue with deployed FastAPI version
This commit is contained in:
Automated Action 2025-06-20 11:59:33 +00:00
parent dfabc89d07
commit 7c96bd9af2

37
main.py
View File

@ -1,8 +1,7 @@
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.base import BaseHTTPMiddleware
from app.db.session import engine
from app.db.base import Base
from app.routers import monitors, checks, scheduler
@ -16,33 +15,6 @@ logger = logging.getLogger(__name__)
Base.metadata.create_all(bind=engine)
class CORSMiddleware2(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Handle preflight requests
if request.method == "OPTIONS":
response = Response()
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = (
"GET, POST, PUT, DELETE, OPTIONS"
)
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Max-Age"] = "3600"
return response
# Process the request
response = await call_next(request)
# Add CORS headers to the response
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = (
"GET, POST, PUT, DELETE, OPTIONS"
)
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Expose-Headers"] = "*"
return response
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
@ -62,10 +34,7 @@ app = FastAPI(
lifespan=lifespan,
)
# Add custom CORS middleware
app.add_middleware(CORSMiddleware2)
# Also add the standard CORS middleware as backup
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
@ -98,8 +67,6 @@ async def health_check():
@app.options("/{full_path:path}")
async def options_handler(full_path: str):
"""Handle preflight OPTIONS requests"""
from fastapi import Response
response = Response()
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"