forked from plotly/plotly.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.py
399 lines (328 loc) · 15.6 KB
/
tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# -*- coding: utf-8 -*-
"""
tools
=====
Functions that USERS will possibly want access to.
"""
from __future__ import absolute_import
import warnings
import six
import copy
from _plotly_utils import optional_imports
import _plotly_utils.exceptions
from _plotly_utils.files import ensure_writable_plotly_dir
from chart_studio import session, utils
from chart_studio.files import CONFIG_FILE, CREDENTIALS_FILE, FILE_CONTENT
ipython_core_display = optional_imports.get_module('IPython.core.display')
sage_salvus = optional_imports.get_module('sage_salvus')
def get_config_defaults():
"""
Convenience function to check current settings against defaults.
Example:
if plotly_domain != get_config_defaults()['plotly_domain']:
# do something
"""
return dict(FILE_CONTENT[CONFIG_FILE]) # performs a shallow copy
def ensure_local_plotly_files():
"""Ensure that filesystem is setup/filled out in a valid way.
If the config or credential files aren't filled out, then write them
to the disk.
"""
if ensure_writable_plotly_dir():
for fn in [CREDENTIALS_FILE, CONFIG_FILE]:
utils.ensure_file_exists(fn)
contents = utils.load_json_dict(fn)
contents_orig = contents.copy()
for key, val in list(FILE_CONTENT[fn].items()):
# TODO: removed type checking below, may want to revisit
if key not in contents:
contents[key] = val
contents_keys = list(contents.keys())
for key in contents_keys:
if key not in FILE_CONTENT[fn]:
del contents[key]
# save only if contents has changed.
# This is to avoid .credentials or .config file to be overwritten randomly,
# which we constantly keep experiencing
# (sync issues? the file might be locked for writing by other process in file._permissions)
if contents_orig.keys() != contents.keys():
utils.save_json_dict(fn, contents)
else:
warnings.warn("Looks like you don't have 'read-write' permission to "
"your 'home' ('~') directory or to our '~/.plotly' "
"directory. That means plotly's python api can't setup "
"local configuration files. No problem though! You'll "
"just have to sign-in using 'plotly.plotly.sign_in()'. "
"For help with that: 'help(plotly.plotly.sign_in)'."
"\nQuestions? Visit https://support.plot.ly")
### credentials tools ###
def set_credentials_file(username=None,
api_key=None,
stream_ids=None,
proxy_username=None,
proxy_password=None):
"""Set the keyword-value pairs in `~/.plotly_credentials`.
:param (str) username: The username you'd use to sign in to Plotly
:param (str) api_key: The api key associated with above username
:param (list) stream_ids: Stream tokens for above credentials
:param (str) proxy_username: The un associated with with your Proxy
:param (str) proxy_password: The pw associated with your Proxy un
"""
if not ensure_writable_plotly_dir():
raise _plotly_utils.exceptions.PlotlyError("You don't have proper file permissions "
"to run this function.")
ensure_local_plotly_files() # make sure what's there is OK
credentials = get_credentials_file()
if isinstance(username, six.string_types):
credentials['username'] = username
if isinstance(api_key, six.string_types):
credentials['api_key'] = api_key
if isinstance(proxy_username, six.string_types):
credentials['proxy_username'] = proxy_username
if isinstance(proxy_password, six.string_types):
credentials['proxy_password'] = proxy_password
if isinstance(stream_ids, (list, tuple)):
credentials['stream_ids'] = stream_ids
utils.save_json_dict(CREDENTIALS_FILE, credentials)
ensure_local_plotly_files() # make sure what we just put there is OK
def get_credentials_file(*args):
"""Return specified args from `~/.plotly_credentials`. as dict.
Returns all if no arguments are specified.
Example:
get_credentials_file('username')
"""
# Read credentials from file if possible
credentials = utils.load_json_dict(CREDENTIALS_FILE, *args)
if not credentials:
# Credentials could not be read, use defaults
credentials = copy.copy(FILE_CONTENT[CREDENTIALS_FILE])
return credentials
def reset_credentials_file():
ensure_local_plotly_files() # make sure what's there is OK
utils.save_json_dict(CREDENTIALS_FILE, {})
ensure_local_plotly_files() # put the defaults back
### config tools ###
def set_config_file(plotly_domain=None,
plotly_streaming_domain=None,
plotly_api_domain=None,
plotly_ssl_verification=None,
plotly_proxy_authorization=None,
world_readable=None,
sharing=None,
auto_open=None):
"""Set the keyword-value pairs in `~/.plotly/.config`.
:param (str) plotly_domain: ex - https://plot.ly
:param (str) plotly_streaming_domain: ex - stream.plot.ly
:param (str) plotly_api_domain: ex - https://api.plot.ly
:param (bool) plotly_ssl_verification: True = verify, False = don't verify
:param (bool) plotly_proxy_authorization: True = use plotly proxy auth creds
:param (bool) world_readable: True = public, False = private
"""
if not ensure_writable_plotly_dir():
raise _plotly_utils.exceptions.PlotlyError("You don't have proper file permissions "
"to run this function.")
ensure_local_plotly_files() # make sure what's there is OK
utils.validate_world_readable_and_sharing_settings({
'sharing': sharing, 'world_readable': world_readable})
settings = get_config_file()
if isinstance(plotly_domain, six.string_types):
settings['plotly_domain'] = plotly_domain
elif plotly_domain is not None:
raise TypeError('plotly_domain should be a string')
if isinstance(plotly_streaming_domain, six.string_types):
settings['plotly_streaming_domain'] = plotly_streaming_domain
elif plotly_streaming_domain is not None:
raise TypeError('plotly_streaming_domain should be a string')
if isinstance(plotly_api_domain, six.string_types):
settings['plotly_api_domain'] = plotly_api_domain
elif plotly_api_domain is not None:
raise TypeError('plotly_api_domain should be a string')
if isinstance(plotly_ssl_verification, (six.string_types, bool)):
settings['plotly_ssl_verification'] = plotly_ssl_verification
elif plotly_ssl_verification is not None:
raise TypeError('plotly_ssl_verification should be a boolean')
if isinstance(plotly_proxy_authorization, (six.string_types, bool)):
settings['plotly_proxy_authorization'] = plotly_proxy_authorization
elif plotly_proxy_authorization is not None:
raise TypeError('plotly_proxy_authorization should be a boolean')
if isinstance(auto_open, bool):
settings['auto_open'] = auto_open
elif auto_open is not None:
raise TypeError('auto_open should be a boolean')
# validate plotly_domain and plotly_api_domain
utils.validate_plotly_domains(
{'plotly_domain': plotly_domain, 'plotly_api_domain': plotly_api_domain}
)
if isinstance(world_readable, bool):
settings['world_readable'] = world_readable
settings.pop('sharing')
elif world_readable is not None:
raise TypeError('Input should be a boolean')
if isinstance(sharing, six.string_types):
settings['sharing'] = sharing
elif sharing is not None:
raise TypeError('sharing should be a string')
utils.set_sharing_and_world_readable(settings)
utils.save_json_dict(CONFIG_FILE, settings)
ensure_local_plotly_files() # make sure what we just put there is OK
def get_config_file(*args):
"""Return specified args from `~/.plotly/.config`. as tuple.
Returns all if no arguments are specified.
Example:
get_config_file('plotly_domain')
"""
# Read config from file if possible
config = utils.load_json_dict(CONFIG_FILE, *args)
if not config:
# Config could not be read, use defaults
config = copy.copy(FILE_CONTENT[CONFIG_FILE])
return config
def reset_config_file():
ensure_local_plotly_files() # make sure what's there is OK
f = open(CONFIG_FILE, 'w')
f.close()
ensure_local_plotly_files() # put the defaults back
### embed tools ###
def get_embed(file_owner_or_url, file_id=None, width="100%", height=525):
"""Returns HTML code to embed figure on a webpage as an <iframe>
Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair.
Since each file is given a corresponding unique url, you may also simply
pass a valid plotly url as the first argument.
Note, if you're using a file_owner string as the first argument, you MUST
specify a `file_id` keyword argument. Else, if you're using a url string
as the first argument, you MUST NOT specify a `file_id` keyword argument,
or file_id must be set to Python's None value.
Positional arguments:
file_owner_or_url (string) -- a valid plotly username OR a valid plotly url
Keyword arguments:
file_id (default=None) -- an int or string that can be converted to int
if you're using a url, don't fill this in!
width (default="100%") -- an int or string corresp. to width of the figure
height (default="525") -- same as width but corresp. to the height of the
figure
"""
plotly_rest_url = (session.get_session_config().get('plotly_domain') or
get_config_file()['plotly_domain'])
if file_id is None: # assume we're using a url
url = file_owner_or_url
if url[:len(plotly_rest_url)] != plotly_rest_url:
raise _plotly_utils.exceptions.PlotlyError(
"Because you didn't supply a 'file_id' in the call, "
"we're assuming you're trying to snag a figure from a url. "
"You supplied the url, '{0}', we expected it to start with "
"'{1}'."
"\nRun help on this function for more information."
"".format(url, plotly_rest_url))
urlsplit = six.moves.urllib.parse.urlparse(url)
file_owner = urlsplit.path.split('/')[1].split('~')[1]
file_id = urlsplit.path.split('/')[2]
# to check for share_key we check urlsplit.query
query_dict = six.moves.urllib.parse.parse_qs(urlsplit.query)
if query_dict:
share_key = query_dict['share_key'][-1]
else:
share_key = ''
else:
file_owner = file_owner_or_url
share_key = ''
try:
test_if_int = int(file_id)
except ValueError:
raise _plotly_utils.exceptions.PlotlyError(
"The 'file_id' argument was not able to be converted into an "
"integer number. Make sure that the positional 'file_id' argument "
"is a number that can be converted into an integer or a string "
"that can be converted into an integer."
)
if int(file_id) < 0:
raise _plotly_utils.exceptions.PlotlyError(
"The 'file_id' argument must be a non-negative number."
)
if share_key is '':
s = ("<iframe id=\"igraph\" scrolling=\"no\" style=\"border:none;\" "
"seamless=\"seamless\" "
"src=\"{plotly_rest_url}/"
"~{file_owner}/{file_id}.embed\" "
"height=\"{iframe_height}\" width=\"{iframe_width}\">"
"</iframe>").format(
plotly_rest_url=plotly_rest_url,
file_owner=file_owner, file_id=file_id,
iframe_height=height, iframe_width=width)
else:
s = ("<iframe id=\"igraph\" scrolling=\"no\" style=\"border:none;\" "
"seamless=\"seamless\" "
"src=\"{plotly_rest_url}/"
"~{file_owner}/{file_id}.embed?share_key={share_key}\" "
"height=\"{iframe_height}\" width=\"{iframe_width}\">"
"</iframe>").format(
plotly_rest_url=plotly_rest_url,
file_owner=file_owner, file_id=file_id, share_key=share_key,
iframe_height=height, iframe_width=width)
return s
def embed(file_owner_or_url, file_id=None, width="100%", height=525):
"""Embeds existing Plotly figure in IPython Notebook
Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair.
Since each file is given a corresponding unique url, you may also simply
pass a valid plotly url as the first argument.
Note, if you're using a file_owner string as the first argument, you MUST
specify a `file_id` keyword argument. Else, if you're using a url string
as the first argument, you MUST NOT specify a `file_id` keyword argument,
or file_id must be set to Python's None value.
Positional arguments:
file_owner_or_url (string) -- a valid plotly username OR a valid plotly url
Keyword arguments:
file_id (default=None) -- an int or string that can be converted to int
if you're using a url, don't fill this in!
width (default="100%") -- an int or string corresp. to width of the figure
height (default="525") -- same as width but corresp. to the height of the
figure
"""
try:
s = get_embed(file_owner_or_url, file_id=file_id, width=width,
height=height)
# see if we are in the SageMath Cloud
if sage_salvus:
return sage_salvus.html(s, hide=False)
except:
pass
if ipython_core_display:
if file_id:
plotly_domain = (
session.get_session_config().get('plotly_domain') or
get_config_file()['plotly_domain']
)
url = "{plotly_domain}/~{un}/{fid}".format(
plotly_domain=plotly_domain,
un=file_owner_or_url,
fid=file_id)
else:
url = file_owner_or_url
return PlotlyDisplay(url, width, height)
else:
if (get_config_defaults()['plotly_domain']
!= session.get_session_config()['plotly_domain']):
feedback_contact = 'Visit support.plot.ly'
else:
# different domain likely means enterprise
feedback_contact = 'Contact your On-Premise account executive'
warnings.warn(
"Looks like you're not using IPython or Sage to embed this "
"plot. If you just want the *embed code*,\ntry using "
"`get_embed()` instead."
'\nQuestions? {}'.format(feedback_contact))
### graph_objs related tools ###
if ipython_core_display:
class PlotlyDisplay(ipython_core_display.HTML):
"""An IPython display object for use with plotly urls
PlotlyDisplay objects should be instantiated with a url for a plot.
IPython will *choose* the proper display representation from any
Python object, and using provided methods if they exist. By defining
the following, if an HTML display is unusable, the PlotlyDisplay
object can provide alternate representations.
"""
def __init__(self, url, width, height):
self.resource = url
self.embed_code = get_embed(url, width=width, height=height)
super(PlotlyDisplay, self).__init__(data=self.embed_code)
def _repr_html_(self):
return self.embed_code