Skip to content

Commit f5aefdd

Browse files
committedJan 8, 2016
use thread-local data, use safer tmpfile
1 parent e29ac1a commit f5aefdd

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed
 

‎nikola/state.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
import json
3030
import os
3131
import shutil
32+
import tempfile
33+
import threading
3234

3335
from . import utils
3436

@@ -47,33 +49,35 @@ def __init__(self, path):
4749
"""Where do you want it persisted."""
4850
self._path = path
4951
utils.makedirs(os.path.dirname(path))
50-
self.data = {}
52+
self._local = threading.local()
53+
self._local.data = {}
5154

5255
def get(self, key):
5356
"""Get data stored in key."""
5457
self._read()
55-
return self.data.get(key)
58+
return self._local.data.get(key)
5659

5760
def set(self, key, value):
5861
"""Store value in key."""
5962
self._read()
60-
self.data[key] = value
63+
self._local.data[key] = value
6164
self._save()
6265

6366
def delete(self, key):
6467
"""Delete key and the value it contains."""
6568
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)
6871
self._save()
6972

7073
def _read(self):
7174
if os.path.isfile(self._path):
7275
with open(self._path) as inf:
73-
self.data = json.load(inf)
76+
self._local.data = json.load(inf)
7477

7578
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

Comments
 (0)
Please sign in to comment.