Skip to content

Commit d928bf5

Browse files
committed
Add json storage definer
1 parent 5b35bd0 commit d928bf5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

definers/json_storage.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import os.path
2+
import pickle
3+
from typing import List
4+
5+
from models.definer import DefinerStorage, NotFoundException
6+
from models.word import WordDefinition
7+
8+
9+
class JsonDefinerStorage(DefinerStorage):
10+
def exists(self, word: str) -> bool:
11+
return os.path.exists(self.__get_word_store_location(word))
12+
13+
def __init__(self):
14+
self.__storage_location = os.path.join(os.path.dirname(__file__), '../data/definitions')
15+
16+
if not os.path.exists(self.__storage_location):
17+
os.makedirs(self.__storage_location)
18+
19+
def store(self, word: str, definitions: List[WordDefinition]):
20+
with open(self.__get_word_store_location(word), 'wb') as f:
21+
pickle.dump(definitions, f)
22+
23+
def define(self, word) -> List[WordDefinition]:
24+
word_location = self.__get_word_store_location(word)
25+
26+
if not self.exists(word):
27+
raise NotFoundException(f"Word {word} not found")
28+
29+
with open(word_location, 'rb') as f:
30+
return pickle.load(f)
31+
32+
def __get_word_store_location(self, word: str):
33+
return os.path.join(self.__storage_location, f"{word}.bin")

0 commit comments

Comments
 (0)