1+ from contextlib import asynccontextmanager
12from fastapi import FastAPI
23from fastapi .middleware .cors import CORSMiddleware
34from src .routers import movies
4- from src .utils .errorHandler import register_error_handlers , create_error_response
5+ from src .utils .errorHandler import register_error_handlers
56from src .database .mongo_client import db , get_collection
6- import traceback
7+
78import os
89from dotenv import load_dotenv
910
1011# Load environment variables from .env file
1112load_dotenv ()
1213
13- app = FastAPI ()
1414
15- # Add CORS middleware
16- cors_origins = os .getenv ("CORS_ORIGINS" , "http://localhost:3000,http://localhost:3001" ).split ("," )
17- app .add_middleware (
18- CORSMiddleware ,
19- allow_origins = [origin .strip () for origin in cors_origins ], # Load from environment variable
20- allow_credentials = True ,
21- allow_methods = ["*" ],
22- allow_headers = ["*" ],
23- )
15+ @asynccontextmanager
16+ async def lifespan (app : FastAPI ):
17+ # Startup: Create search indexes
18+ await ensure_search_index ()
19+ await vector_search_index ()
20+ yield
21+ # Shutdown: Clean up resources if needed
22+ # Add any cleanup code here
2423
25- register_error_handlers (app )
26- app .include_router (movies .router , prefix = "/api/movies" , tags = ["movies" ])
2724
28-
29- @app .on_event ("startup" )
3025async def ensure_search_index ():
3126 try :
3227 movies_collection = db .get_collection ("movies" )
@@ -64,7 +59,7 @@ async def ensure_search_index():
6459 f"Please check your MongoDB Atlas configuration and ensure the cluster supports search indexes."
6560 )
6661
67- @ app . on_event ( "startup" )
62+
6863async def vector_search_index ():
6964 """
7065 Creates vector search index on application startup if it doesn't already exist.
@@ -98,7 +93,7 @@ async def vector_search_index():
9893 }
9994
10095 # Create the index
101- result = await embedded_movies_collection .create_search_index (index_definition )
96+ await embedded_movies_collection .create_search_index (index_definition )
10297
10398 except Exception as e :
10499 raise RuntimeError (
@@ -108,3 +103,19 @@ async def vector_search_index():
108103 f"and verify the 'embedded_movies' collection exists with the required embedding field."
109104 )
110105
106+
107+ app = FastAPI (lifespan = lifespan )
108+
109+ # Add CORS middleware
110+ cors_origins = os .getenv ("CORS_ORIGINS" , "http://localhost:3000,http://localhost:3001" ).split ("," )
111+ app .add_middleware (
112+ CORSMiddleware ,
113+ allow_origins = [origin .strip () for origin in cors_origins ], # Load from environment variable
114+ allow_credentials = True ,
115+ allow_methods = ["*" ],
116+ allow_headers = ["*" ],
117+ )
118+
119+ register_error_handlers (app )
120+ app .include_router (movies .router , prefix = "/api/movies" , tags = ["movies" ])
121+
0 commit comments