-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbinterface.py
More file actions
109 lines (85 loc) · 3.44 KB
/
Copy pathdbinterface.py
File metadata and controls
109 lines (85 loc) · 3.44 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from typing import Any, Dict, List
from bson.objectid import ObjectId
from pymongo import MongoClient
from backend import settings
from backend.task import CreateTask, Task, TaskDict, TaskId, UpdateTask
def _document_to_task(doc: Dict):
task = Task(
id=str(doc["_id"]),
name=doc["name"],
isCompleted=doc["isCompleted"],
)
return task
def _task_to_document(task: Task | CreateTask | UpdateTask) -> Dict:
task_dict = dict(task)
task_dict = {key: value for key, value in task_dict.items() if value is not None}
return task_dict
def _id_to_query(id: TaskId) -> Dict[str, ObjectId] | None:
"""Converts an ID string to a valid MongoDB query
Returns query dictionary or `None` if the provided `id` is not a valid :class:`ObjectId`
"""
try:
oid = ObjectId(id)
except:
return None
return {"_id": oid}
class MongoDBInterface:
def __init__(self, db_name: str = "todo_app", mongodb_client_factory: Any = None):
# Provide the mongodb atlas url to connect python to mongodb using pymongo
CONNECTION_STRING = settings.MONGODB_URI
print(f"MOGODB_URI: {CONNECTION_STRING}")
# Create a connection using MongoClient. You can import MongoClient or use pymongo.MongoClient
mongodb_client_factory = mongodb_client_factory or MongoClient
self._client: MongoClient[Any] = mongodb_client_factory(
CONNECTION_STRING, connectTimeoutMs=5000, timeoutMs=5000
)
# Create the database for our example (we will use the same database throughout the tutorial
self._db = self._client[db_name]
self._task_collection = self._db["tasks"]
def get_task(self, id: TaskId) -> Task | None:
query = _id_to_query(id)
if query is None:
return None
result = self._task_collection.find_one(query)
if result is None:
return None
task = _document_to_task(result)
return task
def create_task(self, task: CreateTask) -> Task:
result = self._task_collection.insert_one(_task_to_document(task))
return Task(
id=str(result.inserted_id), name=task.name, isCompleted=task.isCompleted
)
def delete_task(self, id: TaskId) -> int:
query = _id_to_query(id)
if query is None:
return 0
result = self._task_collection.delete_one(query)
return result.deleted_count
def update_task(self, id: TaskId, update_params: UpdateTask) -> Task | None:
query = _id_to_query(id)
if query is None:
return None
update = {"$set": _task_to_document(update_params)}
response = self._task_collection.update_one(query, update, upsert=False)
if response.matched_count == 0:
return None
return self.get_task(id)
def num_tasks(self) -> int:
return self._task_collection.count_documents({})
def get_all_tasks(self) -> TaskDict:
task_list = self._task_collection.find()
task_dict = {t["_id"]: _document_to_task(t) for t in task_list}
return task_dict
def print_tasks(self):
for task in self._task_collection.find():
print(task)
def set_tasks(self, tasks: List[CreateTask]):
self._task_collection.drop()
for task in tasks:
self.create_task(task)
def close(self):
self._client.close()
if __name__ == "__main__":
db = MongoDBInterface()
db.print_tasks()