forked from decodingml/llm-twin-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
34 lines (24 loc) · 948 Bytes
/
db.py
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
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from config import settings
class MongoDatabaseConnector:
"""Singleton class to connect to MongoDB database."""
_instance: MongoClient = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
try:
cls._instance = MongoClient(settings.MONGO_DATABASE_HOST)
except ConnectionFailure as e:
print(f"Couldn't connect to the database: {str(e)}")
raise
print(
f"Connection to database with uri: {settings.MONGO_DATABASE_HOST} successful"
)
return cls._instance
def get_database(self):
return self._instance[settings.MONGO_DATABASE_NAME]
def close(self):
if self._instance:
self._instance.close()
print("Connected to database has been closed.")
connection = MongoDatabaseConnector()