update to python fastpi

This commit is contained in:
Iliyan Angelov
2025-11-16 15:59:05 +02:00
parent 93d4c1df80
commit 98ccd5b6ff
4464 changed files with 773233 additions and 13740 deletions

121
Backend/src/main.py Normal file
View File

@@ -0,0 +1,121 @@
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from sqlalchemy.exc import IntegrityError
from jose.exceptions import JWTError
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
import os
from pathlib import Path
from .config.database import engine, Base
from .middleware.error_handler import (
validation_exception_handler,
integrity_error_handler,
jwt_error_handler,
http_exception_handler,
general_exception_handler
)
# Create database tables
Base.metadata.create_all(bind=engine)
from .routes import auth_routes
# Initialize FastAPI app
app = FastAPI(
title="Hotel Booking API",
description="Hotel booking backend API",
version="1.0.0"
)
# Rate limiting
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# CORS configuration
# Allow multiple origins for development
client_url = os.getenv("CLIENT_URL", "http://localhost:5173")
allowed_origins = [
client_url,
"http://localhost:5173", # Vite default
"http://localhost:3000", # Alternative port
"http://localhost:5174", # Vite alternative
"http://127.0.0.1:5173",
"http://127.0.0.1:3000",
"http://127.0.0.1:5174",
]
# In development, allow all localhost origins using regex
if os.getenv("ENVIRONMENT", "development") == "development":
# For development, use regex to allow any localhost port
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"http://(localhost|127\.0\.0\.1)(:\d+)?",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
else:
# Production: use specific origins
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Serve static files (uploads)
uploads_dir = Path(__file__).parent.parent / "uploads"
uploads_dir.mkdir(exist_ok=True)
app.mount("/uploads", StaticFiles(directory=str(uploads_dir)), name="uploads")
# Exception handlers
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(IntegrityError, integrity_error_handler)
app.add_exception_handler(JWTError, jwt_error_handler)
app.add_exception_handler(Exception, general_exception_handler)
# Health check
@app.get("/health")
async def health_check():
return {
"status": "success",
"message": "Server is running",
"timestamp": __import__("datetime").datetime.utcnow().isoformat()
}
# API Routes
app.include_router(auth_routes.router, prefix="/api")
# Import and include other routes
from .routes import (
room_routes, booking_routes, payment_routes, banner_routes,
favorite_routes, service_routes, promotion_routes, report_routes,
review_routes, user_routes
)
app.include_router(room_routes.router, prefix="/api")
app.include_router(booking_routes.router, prefix="/api")
app.include_router(payment_routes.router, prefix="/api")
app.include_router(banner_routes.router, prefix="/api")
app.include_router(favorite_routes.router, prefix="/api")
app.include_router(service_routes.router, prefix="/api")
app.include_router(promotion_routes.router, prefix="/api")
app.include_router(report_routes.router, prefix="/api")
app.include_router(review_routes.router, prefix="/api")
app.include_router(user_routes.router, prefix="/api")
# Note: FastAPI automatically handles 404s for unmatched routes
# This handler is kept for custom 404 responses but may not be needed
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", 3000))
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True)