29
29
import json
30
30
import os
31
31
import shutil
32
+ import tempfile
33
+ import threading
32
34
33
35
from . import utils
34
36
@@ -47,33 +49,35 @@ def __init__(self, path):
47
49
"""Where do you want it persisted."""
48
50
self ._path = path
49
51
utils .makedirs (os .path .dirname (path ))
50
- self .data = {}
52
+ self ._local = threading .local ()
53
+ self ._local .data = {}
51
54
52
55
def get (self , key ):
53
56
"""Get data stored in key."""
54
57
self ._read ()
55
- return self .data .get (key )
58
+ return self ._local . data .get (key )
56
59
57
60
def set (self , key , value ):
58
61
"""Store value in key."""
59
62
self ._read ()
60
- self .data [key ] = value
63
+ self ._local . data [key ] = value
61
64
self ._save ()
62
65
63
66
def delete (self , key ):
64
67
"""Delete key and the value it contains."""
65
68
self ._read ()
66
- if key in self .data :
67
- self .data .pop (key )
69
+ if key in self ._local . data :
70
+ self ._local . data .pop (key )
68
71
self ._save ()
69
72
70
73
def _read (self ):
71
74
if os .path .isfile (self ._path ):
72
75
with open (self ._path ) as inf :
73
- self .data = json .load (inf )
76
+ self ._local . data = json .load (inf )
74
77
75
78
def _save (self ):
76
- tpath = self ._path + '.tmp'
77
- with open (tpath , 'w' ) as outf :
78
- json .dump (self .data , outf , sort_keys = True , indent = 2 )
79
- shutil .move (tpath , self .path )
79
+ dname = os .path .dirname (self ._path )
80
+ with tempfile .NamedTemporaryFile (dir = dname , delete = False ) as outf :
81
+ tname = outf .name
82
+ json .dump (self ._local .data , outf , sort_keys = True , indent = 2 )
83
+ shutil .move (tname , self .path )
0 commit comments