Skip to content

Commit 2e25dba

Browse files
committed
Move around locks and do a better job ensuring paths exist.
1 parent fe1979f commit 2e25dba

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

Diff for: plotly/tools.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,8 @@ def check_file_permissions():
7272
def ensure_local_plotly_files():
7373
"""Ensure that filesystem is setup/filled out in a valid way"""
7474
if _file_permissions:
75-
if not os.path.isdir(PLOTLY_DIR):
76-
os.mkdir(PLOTLY_DIR)
7775
for fn in [CREDENTIALS_FILE, CONFIG_FILE]:
76+
utils.ensure_file_exists(fn)
7877
contents = utils.load_json_dict(fn)
7978
for key, val in list(_FILE_CONTENT[fn].items()):
8079
# TODO: removed type checking below, may want to revisit

Diff for: plotly/utils.py

+23-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
### incase people are using threadig, we lock file reads
1515
lock = threading.Lock()
1616

17+
1718
### general file setup tools ###
1819

1920
def load_json_dict(filename, *args):
@@ -27,7 +28,7 @@ def load_json_dict(filename, *args):
2728
if not isinstance(data, dict):
2829
data = {}
2930
except:
30-
pass # TODO: issue a warning and bubble it up
31+
data = {} # TODO: issue a warning and bubble it up
3132
lock.release()
3233
if args:
3334
d = dict()
@@ -41,15 +42,32 @@ def load_json_dict(filename, *args):
4142

4243

4344
def save_json_dict(filename, json_dict):
44-
"""Will error if filename is not appropriate, but it's checked elsewhere.
45-
"""
45+
"""Save json to file. Error if path DNE, not a dict, or invalid json."""
4646
if isinstance(json_dict, dict):
47+
# this will raise a TypeError if something goes wrong
48+
json_string = json.dumps(json_dict, indent=4)
4749
lock.acquire()
4850
with open(filename, "w") as f:
49-
f.write(json.dumps(json_dict, indent=4))
51+
f.write(json_string)
5052
lock.release()
5153
else:
52-
raise TypeError("json_dict was not a dictionay. couldn't save.")
54+
raise TypeError("json_dict was not a dictionary. not saving.")
55+
56+
57+
def ensure_file_exists(filename):
58+
"""Given a valid filename, make sure it exists (will create if DNE)."""
59+
if not os.path.exists(filename):
60+
head, tail = os.path.split(filename)
61+
ensure_dir_exists(head)
62+
with open(filename, 'w') as f:
63+
pass # just create the file
64+
65+
66+
def ensure_dir_exists(directory):
67+
"""Given a valid directory path, make sure it exists."""
68+
if dir:
69+
if not os.path.isdir(directory):
70+
os.makedirs(directory)
5371

5472

5573
### Custom JSON encoders ###

0 commit comments

Comments
 (0)