ThejasRao's picture
Update src/agri_predict/config.py
74f026f verified
import os
from dotenv import load_dotenv
from pymongo import MongoClient
import certifi
from datetime import datetime
load_dotenv()
def get_collections():
"""Return a dict with MongoDB collections used by the app.
Loads `MONGO_URI` from environment and connects with TLS CA validation.
Raises RuntimeError if `MONGO_URI` is missing.
"""
mongo_uri = os.getenv("MONGO_URI")
if not mongo_uri:
raise RuntimeError("MONGO_URI is not set in the environment")
# Check if it's a cloud cluster (mongodb+srv or contains mongodb.net)
# Use SSL for cloud clusters, skip SSL for self-hosted instances
if "mongodb+srv" in mongo_uri or "mongodb.net" in mongo_uri:
client = MongoClient(mongo_uri, tlsCAFile=certifi.where())
else:
# Self-hosted MongoDB - connect without SSL
client = MongoClient(mongo_uri)
db = client["AgriPredict"]
# Create indexes for better query performance (safe to call multiple times)
try:
db["WhiteSesame"].create_index([("Reported Date", -1)])
db["WhiteSesame"].create_index([("State Name", 1), ("Reported Date", -1)])
db["WhiteSesame"].create_index([("Market Name", 1), ("Reported Date", -1)])
except Exception:
pass # Indexes might already exist
return {
"collection": db["WhiteSesame"],
"best_params_collection": db["BestParams"],
"best_params_collection_1m": db["BestParams_1m"],
"best_params_collection_3m": db["BestParams_3m"],
"impExp": db["impExp"],
"users_collection": db["user"],
}