1
1
"""Backend for team_db based on a local filesystem directory."""
2
2
3
- import json
4
3
import logging
5
4
import os
6
5
import threading
10
9
from pathlib import Path
11
10
from typing import Any , Callable , Dict , Iterator , Optional , Set
12
11
12
+ import bson
13
+
13
14
from .utils import base64ify , debase64ify , ensure_valid_filename
14
15
15
16
logging .basicConfig (level = logging .DEBUG )
22
23
6 # 2**6 / 10 seconds are 6.4 secs. -> That's how long the db will wait for a log
23
24
)
24
25
DB_PREFIX = "_store_" # Prefix all db files will get
25
- DB_EXTENSION = ".json " # Extension all db files will get
26
+ DB_EXTENSION = ".bson " # Extension all db files will get
26
27
DB_LOCK_EXTENSION = ".lock" # Extension all lock folders will get
27
28
DB_GLOBAL_CACHE_SETTING = True
28
29
@@ -129,9 +130,9 @@ def _dir(self, key: str) -> str:
129
130
"""
130
131
return os .path .join (self .path , DB_PREFIX + base64ify (key , b"+-" ))
131
132
132
- def _dir_jsonname (self , key : str ) -> str :
133
+ def _dir_bsonname (self , key : str ) -> str :
133
134
"""
134
- Return the path for the json db file for this key.
135
+ Return the path for the bson db file for this key.
135
136
136
137
See :func:`_dir`
137
138
"""
@@ -240,7 +241,7 @@ def persist(self) -> None:
240
241
locked = self .is_locked (key ) or self .ignore_locks
241
242
if not locked :
242
243
self .lock (key )
243
- os .remove (self ._dir_jsonname (key ))
244
+ os .remove (self ._dir_bsonname (key ))
244
245
if not locked :
245
246
self .release (key )
246
247
self .logger .debug (f"Deleted { key } from db { self .name } " )
@@ -251,8 +252,8 @@ def persist(self) -> None:
251
252
if not locked :
252
253
self .lock (key )
253
254
try :
254
- with open (self ._dir_jsonname (key ), "wb" ) as f :
255
- f .write (json . dumps ( self ._cache [key ]). encode ( "utf-8" ))
255
+ with open (self ._dir_bsonname (key ), "wb" ) as f :
256
+ f .write (bson . BSON . encode ({ "value" : self ._cache [key ]} ))
256
257
finally :
257
258
if not locked :
258
259
self .release (key )
@@ -272,9 +273,9 @@ def __getitem__(self, key: str) -> Any:
272
273
if not locked :
273
274
self .lock (key )
274
275
try :
275
- with open (self ._dir_jsonname (key ), "rb" ) as f :
276
- val = json . loads (f .read ().decode ("utf-8" ))
277
- except (OSError , json . decoder . JSONDecodeError ) as ex :
276
+ with open (self ._dir_bsonname (key ), "rb" ) as f :
277
+ val = bson . BSON (f .read ()) .decode ()[ "value" ]
278
+ except (OSError , bson . errors . BSONError ) as ex :
278
279
raise KeyError ("Key {} not found - {}" .format (key , ex ))
279
280
finally :
280
281
if not locked :
0 commit comments