Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 093f9dc

Browse files
committed
Added CONFIG_FILE, test for file-read/write permissions.
Credentials are separated from config items.
1 parent 0f15ba3 commit 093f9dc

File tree

1 file changed

+114
-119
lines changed

1 file changed

+114
-119
lines changed

plotly/tools.py

Lines changed: 114 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
Functions that USERS will possibly want access to.
88
99
"""
10+
import os
1011
import os.path
1112
import warnings
1213
from . graph_objs import graph_objs
@@ -21,95 +22,70 @@
2122

2223
PLOTLY_DIR = os.path.join(os.path.expanduser("~"), ".plotly")
2324
CREDENTIALS_FILE = os.path.join(PLOTLY_DIR, ".credentials")
24-
# PLOT_OPTIONS_FILE = os.path.join(PLOTLY_DIR, ".plot_options")
25-
# THEMES_FILE = os.path.join(PLOTLY_DIR, ".themes")
25+
CONFIG_FILE = os.path.join(PLOTLY_DIR, ".config")
26+
TEST_FILE = os.path.join(PLOTLY_DIR, ".permission_test")
2627

28+
# this sets both the DEFAULTS and the TYPES for these items
29+
_FILE_CONTENT = {CREDENTIALS_FILE: {'username': u'',
30+
'api_key': u'',
31+
'stream_ids': []},
32+
CONFIG_FILE: {'plotly_domain': u'https://plot.ly',
33+
'plotly_streaming_domain': u'stream.plot.ly'}}
2734

28-
def ensure_local_plotly_files_exist():
29-
if not os.path.isdir(PLOTLY_DIR):
35+
try:
36+
if not os.path.exists(PLOTLY_DIR):
3037
os.mkdir(PLOTLY_DIR)
31-
for filename in [CREDENTIALS_FILE]: # , PLOT_OPTIONS_FILE, THEMES_FILE]:
32-
if not os.path.exists(filename):
33-
f = open(filename, "w")
34-
f.close()
35-
36-
37-
### config tools ###
38-
39-
# def save_plot_options_file(filename="", fileopt="",
40-
# world_readable=None, auto_open=None):
41-
# """Set the keyword-value pairs in `~/.plotly_plot_options`.
42-
# TODO: the kwarg defaults are confusing - maybe should be left as a kwargs
43-
# TODO: should this be hiddenz?
44-
# """
45-
# ensure_local_plotly_files_exist()
46-
# plot_options = get_plot_options_file()
47-
# if (not plot_options and
48-
# (filename or fileopt or world_readable is not None or
49-
# auto_open is not None)):
50-
# plot_options = {}
51-
# if filename:
52-
# plot_options['filename'] = filename
53-
# if fileopt:
54-
# plot_options['fileopt'] = fileopt
55-
# if world_readable is not None:
56-
# plot_options['world_readable'] = world_readable
57-
# if auto_open is not None:
58-
# plot_options['auto_open'] = auto_open
59-
# utils.save_json(PLOT_OPTIONS_FILE, plot_options)
60-
#
61-
#
62-
# def get_plot_options_file(*args):
63-
# """Return specified args from `~/.plotly_plot_options`. as dict.
64-
#
65-
# Returns all if no arguments are specified.
66-
#
67-
# Example:
68-
# get_plot_options_file('username', 'api_key')
69-
#
70-
# """
71-
# ensure_local_plotly_files_exist()
72-
# options = utils.load_json(PLOT_OPTIONS_FILE, *args)
73-
# if len(options):
74-
# return {str(key): val for key, val in options.items()}
75-
# else:
76-
# return {}
77-
#
78-
#
79-
# def show_plot_options_file(*args):
80-
# """Print specified kwargs from `~/.plotly_plot_options`.
81-
#
82-
# Prints all if no keyword arguments are specified.
83-
#
84-
# """
85-
# ensure_local_plotly_files_exist()
86-
# plot_options = get_plot_options_file(*args)
87-
# if len(args):
88-
# print "The specified keys from your plot options file:\n"
89-
# else:
90-
# print "Your plot options file:\n"
91-
# for key, val in plot_options.items():
92-
# print "\t{}: {}".format(key, val).expandtabs()
38+
f = open(TEST_FILE, 'w')
39+
f.write('testing\n')
40+
f.close()
41+
os.remove(TEST_FILE)
42+
_file_permissions = True
43+
except:
44+
_file_permissions = False
45+
46+
47+
def check_file_permissions():
48+
return _file_permissions
49+
50+
51+
def ensure_local_plotly_files():
52+
"""Ensure that filesystem is setup/filled out in a valid way"""
53+
if _file_permissions:
54+
if not os.path.isdir(PLOTLY_DIR):
55+
os.mkdir(PLOTLY_DIR)
56+
for fn in [CREDENTIALS_FILE, CONFIG_FILE]:
57+
contents = utils.load_json_dict(fn)
58+
for key, val in _FILE_CONTENT[fn].items():
59+
if key not in contents or not isinstance(contents[key], type(val)):
60+
contents[key] = val
61+
contents_keys = contents.keys()
62+
for key in contents_keys:
63+
if key not in _FILE_CONTENT[fn]:
64+
del contents[key]
65+
utils.save_json_dict(fn, contents)
66+
else:
67+
warnings.warn("Looks like you don't have 'write' permission. That "
68+
"means, plotly's python api can't setup local "
69+
"configuration files. No problem though! You'll just "
70+
"have to sign-in using 'plotly.sign_in'.")
9371

9472

9573
### credentials tools ###
9674

97-
def set_credentials_file(username="", api_key="", stream_ids=(), **extra):
75+
def set_credentials_file(username=None, api_key=None, stream_ids=None):
9876
"""Set the keyword-value pairs in `~/.plotly_credentials`.
9977
10078
"""
101-
ensure_local_plotly_files_exist()
79+
ensure_local_plotly_files() # make sure what's there is OK
10280
credentials = get_credentials_file()
103-
if not credentials and (username or api_key or stream_ids):
104-
credentials = {}
105-
if username:
81+
if isinstance(username, (str, unicode)):
10682
credentials['username'] = username
107-
if api_key:
83+
if isinstance(api_key, (str, unicode)):
10884
credentials['api_key'] = api_key
109-
if stream_ids:
85+
if isinstance(stream_ids, (list, tuple)):
11086
credentials['stream_ids'] = stream_ids
111-
credentials.update(extra)
112-
utils.save_json(CREDENTIALS_FILE, credentials)
87+
utils.save_json_dict(CREDENTIALS_FILE, credentials)
88+
ensure_local_plotly_files() # make sure what we just put there is OK
11389

11490

11591
def get_credentials_file(*args):
@@ -121,31 +97,80 @@ def get_credentials_file(*args):
12197
get_credentials_file('username')
12298
12399
"""
124-
ensure_local_plotly_files_exist()
125-
return utils.load_json(CREDENTIALS_FILE, *args)
100+
if _file_permissions:
101+
ensure_local_plotly_files() # make sure what's there is OK
102+
return utils.load_json_dict(CREDENTIALS_FILE, *args)
103+
else:
104+
return _FILE_CONTENT[CREDENTIALS_FILE]
126105

127106

128-
def show_credentials_file(*args):
129-
"""Print specified kwargs from `~/.plotly_credentials`.
107+
def reset_credentials_file():
108+
ensure_local_plotly_files() # make sure what's there is OK
109+
f = open(CREDENTIALS_FILE, 'w')
110+
f.close()
111+
ensure_local_plotly_files() # put the defaults back
130112

131-
Prints all if no keyword arguments are specified.
113+
114+
# def show_credentials_file(*args): # TODO, can we lose this?
115+
# """Print specified kwargs from `~/.plotly_credentials`.
116+
#
117+
# Prints all if no keyword arguments are specified.
118+
#
119+
# """
120+
# ensure_local_plotly_files() # make sure what's there is OK
121+
# credentials = get_credentials_file(*args)
122+
# if len(args):
123+
# print "The specified keys from your credentials file:\n"
124+
# else:
125+
# print "Your credentials file:\n"
126+
# for key, val in credentials.items():
127+
# print "\t{}: {}".format(key, val).expandtabs()
128+
129+
130+
### config tools ###
131+
132+
def set_config_file(plotly_domain=None, plotly_stremaing_domain=None):
133+
"""Set the keyword-value pairs in `~/.plotly/.config`.
134+
135+
"""
136+
ensure_local_plotly_files() # make sure what's there is OK
137+
settings = get_config_file()
138+
if isinstance(plotly_domain, (str, unicode)):
139+
settings['plotly_domain'] = plotly_domain
140+
if isinstance(plotly_stremaing_domain, (str, unicode)):
141+
settings['plotly_streaming_domain'] = plotly_stremaing_domain
142+
utils.save_json_dict(CONFIG_FILE, settings)
143+
ensure_local_plotly_files() # make sure what we just put there is OK
144+
145+
146+
def get_config_file(*args):
147+
"""Return specified args from `~/.plotly_credentials`. as dict.
148+
149+
Returns all if no arguments are specified.
150+
151+
Example:
152+
get_credentials_file('username')
132153
133154
"""
134-
ensure_local_plotly_files_exist()
135-
credentials = get_credentials_file(*args)
136-
if len(args):
137-
print "The specified keys from your credentials file:\n"
155+
if _file_permissions:
156+
ensure_local_plotly_files() # make sure what's there is OK
157+
return utils.load_json_dict(CONFIG_FILE, *args)
138158
else:
139-
print "Your credentials file:\n"
140-
for key, val in credentials.items():
141-
print "\t{}: {}".format(key, val).expandtabs()
159+
return _FILE_CONTENT[CONFIG_FILE]
160+
161+
162+
def reset_config_file():
163+
ensure_local_plotly_files() # make sure what's there is OK
164+
f = open(CONFIG_FILE, 'w')
165+
f.close()
166+
ensure_local_plotly_files() # put the defaults back
142167

143168

144169
### embed tools ###
145170

146171
def get_embed(username, plot_id, width="100%", height=525):
147172
padding = 25
148-
plotly_rest_url = _get_plotly_urls()[0]
173+
plotly_rest_url = get_config_file()['plotly_domain']
149174
if isinstance(width, (int, long)):
150175
s = ("<iframe id=\"igraph\" scrolling=\"no\" style=\"border:none;\""
151176
"seamless=\"seamless\" "
@@ -186,38 +211,8 @@ def embed(username, plot_id, width="100%", height=525):
186211
pass
187212

188213

189-
def _get_plotly_urls(forgiving=False):
190-
''' Return url endpoints for Plotly services.
191-
These endpoints are configurable, and are
192-
retrieved from ~/.plotly/.credentials as:
193-
{
194-
'plotly_rest_url': '...',
195-
'plotly_streaming_url': '...'
196-
}
197-
'''
198-
if forgiving:
199-
try:
200-
config_on_file = get_credentials_file()
201-
except:
202-
config_on_file = {}
203-
else:
204-
config_on_file = get_credentials_file()
205-
206-
if 'plotly_rest_url' in config_on_file:
207-
plotly_rest_url = config_on_file['plotly_rest_url']
208-
else:
209-
plotly_rest_url = 'https://plot.ly'
210-
211-
if 'plotly_streaming_url' in config_on_file:
212-
plotly_streaming_url = config_on_file['plotly_streaming_url']
213-
else:
214-
plotly_streaming_url = 'stream.plot.ly'
215-
216-
return (plotly_rest_url, plotly_streaming_url)
217-
218-
219214
### mpl-related tools ###
220-
@utils.template_doc(plotly_domain=_get_plotly_urls(forgiving=True)[0])
215+
@utils.template_doc(**get_config_file())
221216
def mpl_to_plotly(fig, resize=False, strip_style=False, verbose=False):
222217
"""Convert a matplotlib figure to plotly dictionary and send.
223218

0 commit comments

Comments
 (0)