Skip to content

Commit fc0ab00

Browse files
committed
Merge pull request #107 from plotly/plotly-goes-static
subclass IPython.core.display HTML object for more flexibility.
2 parents b50b491 + d6dd588 commit fc0ab00

File tree

3 files changed

+113
-5
lines changed

3 files changed

+113
-5
lines changed

Diff for: plotly/tests/test_optional/test_ipython/__init__.py

Whitespace-only changes.
+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from __future__ import absolute_import
2+
3+
import plotly.tools as tls
4+
import imghdr
5+
import threading
6+
import unittest
7+
8+
9+
class TestPlotlyDisplay(unittest.TestCase):
10+
11+
def setUp(self):
12+
plot_info = {"un": "plotlyimagetest", "fid": "2"}
13+
url = "https://plot.ly/~{un}/{fid}".format(**plot_info)
14+
self.display_obj = tls.embed(url)
15+
self.results = {}
16+
self.threads = []
17+
self.format_to_func = {
18+
"jpeg": self.jpeg_worker,
19+
"png": self.png_worker,
20+
"svg": self.svg_worker,
21+
"pdf": self.pdf_worker}
22+
23+
def test_plotly_display(self):
24+
for f_format, func in self.format_to_func.items():
25+
self.threads += [threading.Thread(target=func)]
26+
self.threads[-1].setDaemon(True)
27+
self.threads[-1].start()
28+
for thread in self.threads:
29+
thread.join()
30+
for f_format in self.format_to_func:
31+
result = self.results.get(f_format, False)
32+
print("{f_format}: {result}".format(f_format=f_format,
33+
result=result))
34+
assert self.results.get(f_format)
35+
36+
def jpeg_worker(self):
37+
img = self.display_obj._repr_jpeg_()
38+
if imghdr.what('', img) == "jpeg":
39+
self.results["jpeg"] = True
40+
41+
def png_worker(self):
42+
img = self.display_obj._repr_png_()
43+
if imghdr.what('', img) == "png":
44+
self.results["png"] = True
45+
46+
def svg_worker(self):
47+
img = self.display_obj._repr_svg_()
48+
if img[:4] == '<svg':
49+
self.results["svg"] = True
50+
51+
def pdf_worker(self):
52+
img = self.display_obj._repr_pdf_()
53+
if img[:4] == '%PDF':
54+
self.results["pdf"] = True

Diff for: plotly/tools.py

+59-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import os.path
1414
import warnings
1515
import six
16+
import requests
1617

1718
from plotly import utils
1819
from plotly import exceptions
@@ -30,6 +31,12 @@ def warning_on_one_line(message, category, filename, lineno, file=None, line=Non
3031
except ImportError:
3132
_matplotlylib_imported = False
3233

34+
try:
35+
import IPython
36+
_ipython_imported = True
37+
except ImportError:
38+
_ipython_imported = False
39+
3340
PLOTLY_DIR = os.path.join(os.path.expanduser("~"), ".plotly")
3441
CREDENTIALS_FILE = os.path.join(PLOTLY_DIR, ".credentials")
3542
CONFIG_FILE = os.path.join(PLOTLY_DIR, ".config")
@@ -283,11 +290,21 @@ def embed(file_owner_or_url, file_id=None, width="100%", height=525):
283290
return html(s, hide=False)
284291
except:
285292
pass
286-
try:
287-
from IPython.display import HTML, display
288-
display(HTML(s))
289-
except:
290-
pass
293+
if _ipython_imported:
294+
if file_id:
295+
url = "{plotly_domain}/~{un}/{fid}".format(
296+
plotly_domain=get_config_file()['plotly_domain'],
297+
un=file_owner_or_url,
298+
fid=file_id)
299+
else:
300+
url = file_owner_or_url
301+
return PlotlyDisplay(url)
302+
else:
303+
warnings.warn(
304+
"Looks like you're not using IPython or Sage to embed this plot. "
305+
"If you just want the *embed code*, try using `get_embed()` "
306+
"instead."
307+
"\nQuestions? [email protected]")
291308

292309

293310
### mpl-related tools ###
@@ -532,3 +549,40 @@ def _replace_newline(obj):
532549
return s
533550
else:
534551
return obj # we return the actual reference... but DON'T mutate.
552+
553+
554+
if _ipython_imported:
555+
class PlotlyDisplay(IPython.core.display.HTML):
556+
"""An IPython display object for use with plotly urls
557+
558+
PlotlyDisplay objects should be instantiated with a url for a plot.
559+
IPython will *choose* the proper display representation from any
560+
Python object, and using provided methods if they exist. By defining
561+
the following, if an HTML display is unusable, the PlotlyDisplay
562+
object can provide alternate representations.
563+
564+
"""
565+
def __init__(self, url):
566+
self.resource = url
567+
self.embed_code = get_embed(url)
568+
super(PlotlyDisplay, self).__init__(data=self.embed_code)
569+
570+
def _repr_svg_(self):
571+
url = self.resource + ".svg"
572+
res = requests.get(url)
573+
return res.content
574+
575+
def _repr_png_(self):
576+
url = self.resource + ".png"
577+
res = requests.get(url)
578+
return res.content
579+
580+
def _repr_pdf_(self):
581+
url = self.resource + ".pdf"
582+
res = requests.get(url)
583+
return res.content
584+
585+
def _repr_jpeg_(self):
586+
url = self.resource + ".jpeg"
587+
res = requests.get(url)
588+
return res.content

0 commit comments

Comments
 (0)