File size: 3,581 Bytes
9d76e23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import logging  # Imports the logging module for event logging.
from fastapi import FastAPI  # Imports FastAPI, a modern, fast (high-performance) web framework for building APIs.
from fastapi.middleware.cors import CORSMiddleware  # Imports CORSMiddleware for handling Cross-Origin Resource Sharing.

# Imports the API router, recommender system, MongoDB connection, and application settings.
#from api.routes import router
from src.api.routes import router
from src.core.recommender import recommender
from src.database.mongodb import mongodb
from src.config.settings import API_TITLE, API_DESCRIPTION, API_VERSION

# Configure logging settings.
logging.basicConfig(
    level=logging.INFO,  # Sets the minimum logging level to INFO.
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'  # Defines the format for log messages.
)
logger = logging.getLogger(__name__)  # Creates a logger instance for this module.

# Create an instance of the FastAPI application.
app = FastAPI(
    title=API_TITLE,  # Sets the title of the API, loaded from settings.
    description=API_DESCRIPTION,  # Sets the description of the API, loaded from settings.
    version=API_VERSION  # Sets the version of the API, loaded from settings.
)

# Add CORS (Cross-Origin Resource Sharing) middleware to the application.
# This allows requests from different origins (domains) to access the API.
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins. In production, this should be restricted to specific origins for security.
    allow_credentials=True,  # Allows cookies to be included in cross-origin requests.
    allow_methods=["*"],  # Allows all HTTP methods (GET, POST, PUT, DELETE, etc.).
    allow_headers=["*"],  # Allows all headers in requests.
)

# Include the API routes defined in 'src.api.routes.router'.
# This makes the endpoints defined in the router accessible through the app.
app.include_router(router)

@app.on_event("startup")
async def startup_event():
    """
    Asynchronous function to be executed when the application starts up.
    It initializes necessary components like the recommender system.
    """
    try:
        # Initialize recommender
        logger.info("Initializing recommender system...")
        recommender.load_components()
        app.state.recommender = recommender  # Attach recommender to app state
        logger.info("Recommender system initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize recommender system: {e}", exc_info=True)
        raise  # Re-raises the caught exception to halt startup if initialization fails.

@app.on_event("shutdown")
async def shutdown_event():
    """
    Asynchronous function to be executed when the application shuts down.
    It performs cleanup tasks, such as closing database connections.
    """
    try:
        # Close MongoDB connection
        mongodb.close()
        logger.info("MongoDB connection closed")
    except Exception as e:
        # Logs an error if any issue occurs during the shutdown process.
        logger.error(f"Error during shutdown: {e}", exc_info=True)

# This block executes if the script is run directly (e.g., `python main.py`).
if __name__ == "__main__":
    import uvicorn  # Imports Uvicorn, an ASGI server, for running the FastAPI application.
    # Runs the FastAPI application using Uvicorn.
    # host="0.0.0.0" makes the server accessible from any network interface.
    # port=8000 specifies the port on which the server will listen.
    uvicorn.run(app, host="0.0.0.0", port=8000)