-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.py
68 lines (55 loc) · 1.38 KB
/
storage.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
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
import os
from abc import ABC,abstractmethod
from env import env,envpath
class ExistsError(FileExistsError):
pass
class NotFoundError(FileNotFoundError):
pass
class Storage(ABC):
"""
Abstract class for implementing storage backends
"""
def __init__(self):
self.setUp()
@abstractmethod
def setUp(self):
"""
Run @ instantiation
"""
pass
@abstractmethod
def store(self,data:bytes,fid:str)->int:
"""
Store bytes as FID
"""
pass
@abstractmethod
def retrieve(self,fid:str)->bytes:
"""
Retrieve bytes associated with FID
"""
pass
class FileStorage(Storage):
def store(self,data,fid):
p = self._rel_path(fid)
if not os.path.exists(p):
with open(p,"wb") as f:
written = f.write(data)
return written
else:
raise ExistsError
def retrieve(self,fid):
try:
with open(self._rel_path(fid),"rb") as f:
d = f.read()
return d
except FileNotFoundError:
raise NotFoundError
def setUp(self):
self.path = envpath("STORAGE_PATH","storage")
try:
os.makedirs(self.path)
except FileExistsError:
pass
def _rel_path(self,path):
return os.path.join(self.path,path)