Skip to content

Commit 49bdc97

Browse files
committed
made get_grid() to pull grid from cloud and added method in Grid class to retrieve uid from column name
1 parent d17a222 commit 49bdc97

File tree

4 files changed

+47
-148
lines changed

4 files changed

+47
-148
lines changed

plotly/grid_objs/grid_objs.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,3 +187,17 @@ def get_column(self, column_name):
187187
for column in self._columns:
188188
if column.name == column_name:
189189
return column
190+
191+
def get_uid(self, column_name):
192+
"""
193+
Return uid of given column name in grid.
194+
195+
Returns an empty string if either the column name does not exist in
196+
the grid or if the id of the specified column has the empty string id.
197+
"""
198+
uid = ''
199+
for column in self._columns:
200+
if column.name == column_name:
201+
uid = column.id
202+
break
203+
return uid

plotly/offline/offline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def init_notebook_mode(connected=False):
163163
def _plot_html(figure_or_data, config, validate, default_width,
164164
default_height, global_requirejs):
165165
# force no validation if frames is in the call
166-
# TODO - add validation for frames in call - #
166+
# TODO - add validation for frames in call - #605
167167
if 'frames' in figure_or_data:
168168
figure = tools.return_figure_from_figure_or_data(
169169
figure_or_data, False

plotly/plotly/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,5 @@
2222
meta_ops,
2323
file_ops,
2424
get_config,
25-
bad_create_animations,
26-
get_uid_by_col_name
25+
get_grid
2726
)

plotly/plotly/plotly.py

Lines changed: 31 additions & 145 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from plotly.session import (sign_in, update_session_plot_options,
3434
get_session_plot_options, get_session_credentials,
3535
get_session_config)
36+
from plotly.grid_objs import grid_objs
3637

3738
__all__ = None
3839

@@ -384,6 +385,7 @@ def get_figure(file_owner_or_url, file_id=None, raw=False):
384385
raise exceptions.PlotlyError(
385386
"The 'file_id' argument must be a non-negative number."
386387
)
388+
387389
response = requests.get(plotly_rest_url + resource,
388390
headers=headers,
389391
verify=get_config()['plotly_ssl_verification'])
@@ -1452,160 +1454,44 @@ def _send_to_plotly(figure, **plot_options):
14521454
return r
14531455

14541456

1455-
def bad_create_animations(fig, kwargs, payload):
1457+
def get_grid(grid_url, raw=False):
14561458
"""
1457-
Makes a post to GRIDS and PLOTS if frames is in the figure.
1459+
Returns a JSON figure representation for the specified grid.
14581460
1459-
This function bypasses the current '/clientresp' route of making a POST
1460-
request to return back a url. Instead, the V2 REST API is used if frames
1461-
is part of the figure's keys. Currently, 'error', 'message' and 'warning'
1462-
are hard codded to the empty string.
1463-
"""
1464-
url_v2_plot = "https://api.plot.ly/v2/plots"
1465-
url_v2_grid = "https://api.plot.ly/v2/grids"
1466-
auth = HTTPBasicAuth(str(payload['un']), str(payload['key']))
1467-
headers = {'Plotly-Client-Platform': 'python'}
1468-
1469-
# add layout if not in fig
1470-
if 'layout' not in fig:
1471-
fig['layout'] = {}
1472-
1473-
# make a copy of fig
1474-
fig_with_uids = copy.deepcopy(fig)
1475-
1476-
# make grid
1477-
cols_dict = {}
1478-
frames_cols_dict = {}
1479-
counter = 0
1480-
trace_num = 0
1481-
for trace in fig['data']:
1482-
for var in ['x', 'y']:
1483-
if 'name' in trace:
1484-
cols_dict["{name}, {x_or_y}".format(name=trace['name'],
1485-
x_or_y=var)] = {
1486-
"data": list(trace[var]), "order": counter
1487-
}
1488-
else:
1489-
cols_dict["Trace {num}, {x_or_y}".format(num=trace_num,
1490-
x_or_y=var)] = {
1491-
"data": list(trace[var]), "order": counter
1492-
}
1493-
counter += 1
1494-
trace_num += 1
1495-
1496-
# add frames data to grid
1497-
for j in range(len(fig['frames'])):
1498-
for var in ['x', 'y']:
1499-
if 'name' in fig['frames'][j]['data']:
1500-
cols_dict["{name}, {x_or_y}".format(
1501-
name=fig['frames'][j]['data'][0]['name'], x_or_y=var
1502-
)] = {
1503-
"data": list(fig['frames'][j]['data'][0][var]),
1504-
"order": counter
1505-
}
1506-
else:
1507-
cols_dict["Trace {num}, {x_or_y}".format(
1508-
num=trace_num, x_or_y=var
1509-
)] = {
1510-
"data": list(fig['frames'][j]['data'][0][var]),
1511-
"order": counter
1512-
}
1513-
counter += 1
1514-
trace_num += 1
1515-
1516-
grid_info = {
1517-
"data": {"cols": cols_dict},
1518-
"world_readable": True
1519-
}
1520-
1521-
r = requests.post(url_v2_grid, auth=auth,
1522-
headers=headers, json=grid_info)
1523-
r_dict = json.loads(r.text)
1524-
1525-
# make plot
1526-
fid = r_dict['file']['fid']
1527-
cols_index = 0
1528-
for trace in fig_with_uids['data']:
1529-
if 'x' in trace:
1530-
del trace['x']
1531-
if 'y' in trace:
1532-
del trace['y']
1533-
1534-
trace["xsrc"] = "{fid}:{idlocal}".format(
1535-
fid=fid, idlocal=r_dict['file']['cols'][cols_index]['uid']
1536-
)
1537-
trace["ysrc"] = "{fid}:{idlocal}".format(
1538-
fid=fid, idlocal=r_dict['file']['cols'][cols_index + 1]['uid']
1539-
)
1540-
cols_index += 2
1541-
1542-
# replace data in frames by grid ids
1543-
for j in range(len(fig['frames'])):
1544-
if 'x' in fig_with_uids['frames'][j]['data'][0]:
1545-
del fig_with_uids['frames'][j]['data'][0]['x']
1546-
if 'y' in fig_with_uids['frames'][j]['data'][0]:
1547-
del fig_with_uids['frames'][j]['data'][0]['y']
1548-
1549-
fig_with_uids['frames'][j]['data'][0]["xsrc"] = "{fid}:{idlocal}".format(
1550-
fid=fid, idlocal=r_dict['file']['cols'][cols_index]['uid']
1551-
)
1552-
fig_with_uids['frames'][j]['data'][0]["ysrc"] = "{fid}:{idlocal}".format(
1553-
fid=fid, idlocal=r_dict['file']['cols'][cols_index + 1]['uid']
1554-
)
1555-
cols_index += 2
1556-
1557-
plots_info = {
1558-
"figure": fig_with_uids,
1559-
"world_readable": json.loads(kwargs)['world_readable']
1560-
}
1561-
1562-
r = requests.post(url_v2_plot, auth=auth,
1563-
headers=headers, json=plots_info)
1564-
1565-
r_json = json.loads(r.text)
1566-
1567-
r_dict = {
1568-
'error': '',
1569-
'filename': json.loads(kwargs)['filename'],
1570-
'message': '',
1571-
'url': r_json['file']['web_url'],
1572-
'warning': ''
1573-
}
1574-
1575-
return r_dict
1576-
1577-
1578-
def get_uid_by_col_name(grid_url, col_name):
1579-
"""
1580-
Search for a column of a grid by name and return the uid of the column.
1461+
:param (bool) raw: if False, will output a Grid instance of the JSON grid
1462+
being retrieved. If True, raw JSON will be returned.
15811463
"""
15821464
credentials = get_credentials()
15831465
validate_credentials(credentials)
1584-
auth = HTTPBasicAuth(credentials['username'], credentials['api_key'])
1585-
headers = {'Plotly-Client-Platform': 'python'}
1466+
username, api_key = credentials['username'], credentials['api_key']
1467+
headers = {'plotly-username': username,
1468+
'plotly-apikey': api_key,
1469+
'plotly-version': version.__version__,
1470+
'plotly-platform': 'python'}
15861471
upload_url = _api_v2.api_url('grids')
15871472

15881473
tilda_index = grid_url.find('~')
1589-
fid_in_url = grid_url[tilda_index + 1: -1].replace('/', ':')
1590-
get_url = upload_url + '/' + fid_in_url
1591-
1592-
r = requests.get(get_url, auth=auth, headers=headers)
1593-
r_text = json.loads(r.text)
1594-
1595-
col_uid = ''
1596-
for col in r_text['cols']:
1597-
if col_name == col['name']:
1598-
col_uid = col['uid']
1599-
break
1600-
1601-
all_col_names = ([r_text['cols'][j]['name'] for j in
1602-
range(len(r_text['cols']))])
1603-
if col_uid == '':
1604-
raise exceptions.PlotlyError(
1605-
'The col_name does not match with any column name in your grid. '
1606-
'The column names in your grid are {}'.format(all_col_names))
1474+
if grid_url[-1] == '/':
1475+
fid_in_url = grid_url[tilda_index + 1: -1].replace('/', ':')
1476+
else:
1477+
fid_in_url = grid_url[tilda_index + 1: len(grid_url)]
1478+
fid_in_url = fid_in_url.replace('/', ':')
1479+
get_url = upload_url + '/' + fid_in_url + '/content'
1480+
1481+
r = requests.get(get_url, headers=headers)
1482+
json_res = json.loads(r.text)
1483+
if raw is False:
1484+
# create a new grid
1485+
new_grid = grid_objs.Grid(
1486+
[grid_objs.Column(json_res['cols'][column]['data'], column)
1487+
for column in json_res['cols']]
1488+
)
1489+
# fill in uids
1490+
for column in new_grid:
1491+
column.id = json_res['cols'][column.name]['uid']
1492+
return new_grid
16071493
else:
1608-
return col_uid
1494+
return json_res
16091495

16101496

16111497
def _open_url(url):

0 commit comments

Comments
 (0)