Skip to content

Commit fe1979f

Browse files
committed
Add a lock for folks using threading. Mucho helpful.
I can't see any *downside* to including a lock here. Basically, it just says that two threads running in parallel can't touch the code between the lock.acquire() <--> lock.release() statements concurrently. We use it in low-level util functions to prevent concurrent file reads/writes. This was a bug that showed up while running our auto-documentation examples.
1 parent 8978802 commit fe1979f

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

Diff for: plotly/tools.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,7 @@ def get_credentials_file(*args):
134134

135135
def reset_credentials_file():
136136
ensure_local_plotly_files() # make sure what's there is OK
137-
f = open(CREDENTIALS_FILE, 'w')
138-
f.close()
137+
utils.save_json_dict(CREDENTIALS_FILE, {})
139138
ensure_local_plotly_files() # put the defaults back
140139

141140

Diff for: plotly/utils.py

+7
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,26 @@
99
import json
1010
import os.path
1111
import sys
12+
import threading
1213

14+
### incase people are using threadig, we lock file reads
15+
lock = threading.Lock()
1316

1417
### general file setup tools ###
1518

1619
def load_json_dict(filename, *args):
1720
"""Checks if file exists. Returns {} if something fails."""
1821
data = {}
1922
if os.path.exists(filename):
23+
lock.acquire()
2024
with open(filename, "r") as f:
2125
try:
2226
data = json.load(f)
2327
if not isinstance(data, dict):
2428
data = {}
2529
except:
2630
pass # TODO: issue a warning and bubble it up
31+
lock.release()
2732
if args:
2833
d = dict()
2934
for key in args:
@@ -39,8 +44,10 @@ def save_json_dict(filename, json_dict):
3944
"""Will error if filename is not appropriate, but it's checked elsewhere.
4045
"""
4146
if isinstance(json_dict, dict):
47+
lock.acquire()
4248
with open(filename, "w") as f:
4349
f.write(json.dumps(json_dict, indent=4))
50+
lock.release()
4451
else:
4552
raise TypeError("json_dict was not a dictionay. couldn't save.")
4653

0 commit comments

Comments
 (0)