-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
55 lines (44 loc) · 1.66 KB
/
database.py
File metadata and controls
55 lines (44 loc) · 1.66 KB
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
"""
MongoDB database connection and operations
"""
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from config import settings
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MongoDB:
client: MongoClient = None
def __init__(self):
self.client = None
self.db = None
self.collection = None
def connect(self):
"""Connect to MongoDB"""
try:
self.client = MongoClient(settings.mongodb_url)
# Test the connection
self.client.admin.command('ping')
self.db = self.client[settings.database_name]
self.collection = self.db[settings.collection_name]
logger.info(f"Successfully connected to MongoDB database: {settings.database_name}")
logger.info(f"Using collection: {settings.collection_name}")
except ConnectionFailure as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise
def close(self):
"""Close MongoDB connection"""
if self.client:
self.client.close()
logger.info("MongoDB connection closed")
def insert_evaluation(self, evaluation_data: dict):
"""Insert evaluation data into MongoDB"""
try:
result = self.collection.insert_one(evaluation_data)
logger.info(f"Evaluation inserted with ID: {result.inserted_id}")
return str(result.inserted_id)
except Exception as e:
logger.error(f"Error inserting evaluation: {e}")
raise
# Global database instance
mongodb = MongoDB()