-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
57 lines (44 loc) · 1.71 KB
/
Copy pathdatabase.py
File metadata and controls
57 lines (44 loc) · 1.71 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
"""This module provides the RP To-Do database functionality."""
# todo/database.py
import configparser
import json
from pathlib import Path
from typing import Any, Dict, List, NamedTuple
from todo import DB_READ_ERROR, DB_WRITE_ERROR, JSON_ERROR, SUCCESS
DEFAULT_DB_FILE_PATH = Path.home().joinpath(
"." + Path.home().stem + "_todo.json"
)
class DBResponse(NamedTuple):
todo_list: List[Dict[str, Any]]
error: int
class DatabaseHandler:
def __init__(self, db_path: Path) -> None:
self._db_path = db_path
def read_todos(self) -> DBResponse:
try:
with self._db_path.open("r") as db:
try:
return DBResponse(json.load(db), SUCCESS)
except json.JSONDecodeError: # Catch wrong JSON format
return DBResponse([], JSON_ERROR)
except OSError: # Catch file IO problems
return DBResponse([], DB_READ_ERROR)
def write_todos(self, todo_list: List[Dict[str, Any]]) -> DBResponse:
try:
with self._db_path.open("w") as db:
json.dump(todo_list, db, indent=4)
return DBResponse(todo_list, SUCCESS)
except OSError: # Catch file IO problems
return DBResponse(todo_list, DB_WRITE_ERROR)
def get_database_path(config_file: Path) -> Path:
"""Return the current path to the to-do database."""
config_parser = configparser.ConfigParser()
config_parser.read(config_file)
return Path(config_parser["General"]["database"])
def init_database(db_path: Path) -> int:
"""Create the to-do database."""
try:
db_path.write_text("[]") # Empty to-do list
return SUCCESS
except OSError:
return DB_WRITE_ERROR