Skip to content

Add a lock for folks using threading. Mucho helpful. #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 19, 2014
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions plotly/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,7 @@ def get_credentials_file(*args):

def reset_credentials_file():
ensure_local_plotly_files() # make sure what's there is OK
f = open(CREDENTIALS_FILE, 'w')
f.close()
utils.save_json_dict(CREDENTIALS_FILE, {})
ensure_local_plotly_files() # put the defaults back


Expand Down
7 changes: 7 additions & 0 deletions plotly/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,26 @@
import json
import os.path
import sys
import threading
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

threading is part of the standard lib, so yeah why not ... 👍


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

### general file setup tools ###

def load_json_dict(filename, *args):
"""Checks if file exists. Returns {} if something fails."""
data = {}
if os.path.exists(filename):
lock.acquire()
with open(filename, "r") as f:
try:
data = json.load(f)
if not isinstance(data, dict):
data = {}
except:
pass # TODO: issue a warning and bubble it up
lock.release()
if args:
d = dict()
for key in args:
Expand All @@ -39,8 +44,10 @@ def save_json_dict(filename, json_dict):
"""Will error if filename is not appropriate, but it's checked elsewhere.
"""
if isinstance(json_dict, dict):
lock.acquire()
with open(filename, "w") as f:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoops. we assume this directory is accessible here. I'm pretty sure there's a check for this higher-up, but that's not obvious and should be changed.

f.write(json.dumps(json_dict, indent=4))
lock.release()
else:
raise TypeError("json_dict was not a dictionay. couldn't save.")

Expand Down