##// END OF EJS Templates
modified to join urls with '/'.join instead of os.path.join. @takluyver pointed out that while os.path.join does work for this on OS X and Linux, it's not meant for constructing URLs, so fails on Windows where paths are constructed using \ rather than /.
Greg Caporaso -
Show More
@@ -1,146 +1,146 b''
1 """Various display related classes.
1 """Various display related classes.
2
2
3 Authors : MinRK, gregcaporaso
3 Authors : MinRK, gregcaporaso
4 """
4 """
5
5
6 from os import walk
6 from os import walk
7 from os.path import join, exists, isfile, splitext
7 from os.path import exists, isfile, splitext
8
8
9
9
10 class YouTubeVideo(object):
10 class YouTubeVideo(object):
11 """Class for embedding a YouTube Video in an IPython session, based on its video id.
11 """Class for embedding a YouTube Video in an IPython session, based on its video id.
12
12
13 e.g. to embed the video on this page:
13 e.g. to embed the video on this page:
14
14
15 http://www.youtube.com/watch?v=foo
15 http://www.youtube.com/watch?v=foo
16
16
17 you would do:
17 you would do:
18
18
19 vid = YouTubeVideo("foo")
19 vid = YouTubeVideo("foo")
20 display(vid)
20 display(vid)
21 """
21 """
22
22
23 def __init__(self, id, width=400, height=300):
23 def __init__(self, id, width=400, height=300):
24 self.id = id
24 self.id = id
25 self.width = width
25 self.width = width
26 self.height = height
26 self.height = height
27
27
28 def _repr_html_(self):
28 def _repr_html_(self):
29 """return YouTube embed iframe for this video id"""
29 """return YouTube embed iframe for this video id"""
30 return """
30 return """
31 <iframe
31 <iframe
32 width="%i"
32 width="%i"
33 height="%i"
33 height="%i"
34 src="http://www.youtube.com/embed/%s"
34 src="http://www.youtube.com/embed/%s"
35 frameborder="0"
35 frameborder="0"
36 allowfullscreen
36 allowfullscreen
37 ></iframe>
37 ></iframe>
38 """%(self.width, self.height, self.id)
38 """%(self.width, self.height, self.id)
39
39
40 class FileLink(object):
40 class FileLink(object):
41 """Class for embedding a local file link in an IPython session, based on path
41 """Class for embedding a local file link in an IPython session, based on path
42
42
43 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
43 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
44
44
45 you would do:
45 you would do:
46
46
47 local_file = FileLink("my/data.txt")
47 local_file = FileLink("my/data.txt")
48 display(local_file)
48 display(local_file)
49
49
50 or in the HTML notebook, just
50 or in the HTML notebook, just
51
51
52 FileLink("my/data.txt")
52 FileLink("my/data.txt")
53 """
53 """
54
54
55 link_str = "<a href='%s' target='_blank'>%s</a>"
55 link_str = "<a href='%s' target='_blank'>%s</a>"
56
56
57 def __init__(self,
57 def __init__(self,
58 path,
58 path,
59 url_prefix='files',
59 url_prefix='files',
60 result_html_prefix='',
60 result_html_prefix='',
61 result_html_suffix='<br>'):
61 result_html_suffix='<br>'):
62 """
62 """
63 path : path to the file or directory that should be formatted
63 path : path to the file or directory that should be formatted
64 directory_prefix : prefix to be prepended to all files to form a
64 directory_prefix : prefix to be prepended to all files to form a
65 working link [default: 'files']
65 working link [default: 'files']
66 result_html_prefix : text to append to beginning to link
66 result_html_prefix : text to append to beginning to link
67 [default: none]
67 [default: none]
68 result_html_suffix : text to append at the end of link
68 result_html_suffix : text to append at the end of link
69 [default: '<br>']
69 [default: '<br>']
70 """
70 """
71 self.path = path
71 self.path = path
72 self.url_prefix = url_prefix
72 self.url_prefix = url_prefix
73 self.result_html_prefix = result_html_prefix
73 self.result_html_prefix = result_html_prefix
74 self.result_html_suffix = result_html_suffix
74 self.result_html_suffix = result_html_suffix
75
75
76 def _format_path(self):
76 def _format_path(self):
77 fp = join(self.url_prefix,self.path)
77 fp = '/'.join([self.url_prefix,self.path])
78 return ''.join([self.result_html_prefix,
78 return ''.join([self.result_html_prefix,
79 self.link_str % (fp, self.path),
79 self.link_str % (fp, self.path),
80 self.result_html_suffix])
80 self.result_html_suffix])
81
81
82 def _repr_html_(self):
82 def _repr_html_(self):
83 """return link to local file
83 """return link to local file
84 """
84 """
85 if not exists(self.path):
85 if not exists(self.path):
86 return ("Path (<tt>%s</tt>) doesn't exist. "
86 return ("Path (<tt>%s</tt>) doesn't exist. "
87 "It may still be in the process of "
87 "It may still be in the process of "
88 "being generated, or you may have the "
88 "being generated, or you may have the "
89 "incorrect path." % self.path)
89 "incorrect path." % self.path)
90
90
91 return self._format_path()
91 return self._format_path()
92
92
93 # Create an alias for formatting a single directory name as a link.
93 # Create an alias for formatting a single directory name as a link.
94 # Right now this is the same as a formatting for a single file, but
94 # Right now this is the same as a formatting for a single file, but
95 # we'll encorage users to reference these with a different class in
95 # we'll encorage users to reference these with a different class in
96 # case we want to change this in the future.
96 # case we want to change this in the future.
97 DirectoryLink = FileLink
97 DirectoryLink = FileLink
98
98
99 class FileLinks(FileLink):
99 class FileLinks(FileLink):
100 """Class for embedding local file links in an IPython session, based on path
100 """Class for embedding local file links in an IPython session, based on path
101
101
102 e.g. to embed links to files that were generated in the IPython notebook under my/data
102 e.g. to embed links to files that were generated in the IPython notebook under my/data
103
103
104 you would do:
104 you would do:
105
105
106 local_files = FileLinks("my/data")
106 local_files = FileLinks("my/data")
107 display(local_files)
107 display(local_files)
108
108
109 or in the HTML notebook, just
109 or in the HTML notebook, just
110
110
111 FileLinks("my/data")
111 FileLinks("my/data")
112
112
113 """
113 """
114 def __init__(self,
114 def __init__(self,
115 path,
115 path,
116 url_prefix='files',
116 url_prefix='files',
117 included_suffixes=None,
117 included_suffixes=None,
118 result_html_prefix='',
118 result_html_prefix='',
119 result_html_suffix='<br>'):
119 result_html_suffix='<br>'):
120 """
120 """
121 included_suffixes : list of filename suffixes to include when
121 included_suffixes : list of filename suffixes to include when
122 formatting output [default: include all files]
122 formatting output [default: include all files]
123
123
124 See the FileLink (baseclass of LocalDirectory) docstring for
124 See the FileLink (baseclass of LocalDirectory) docstring for
125 information on additional parameters.
125 information on additional parameters.
126 """
126 """
127 self.included_suffixes = included_suffixes
127 self.included_suffixes = included_suffixes
128 FileLink.__init__(self,
128 FileLink.__init__(self,
129 path,
129 path,
130 url_prefix,
130 url_prefix,
131 result_html_prefix,
131 result_html_prefix,
132 result_html_suffix)
132 result_html_suffix)
133
133
134 def _format_path(self):
134 def _format_path(self):
135 result_entries = []
135 result_entries = []
136 for root, dirs, files in walk(self.path):
136 for root, dirs, files in walk(self.path):
137 for fn in files:
137 for fn in files:
138 fp = join(self.url_prefix,root,fn)
138 fp = join(self.url_prefix,root,fn)
139 # if all files are being included, or fp has a suffix
139 # if all files are being included, or fp has a suffix
140 # that is in included_suffix, create a link to fp
140 # that is in included_suffix, create a link to fp
141 if self.included_suffixes == None or \
141 if self.included_suffixes == None or \
142 splitext(fn)[1] in self.included_suffixes:
142 splitext(fn)[1] in self.included_suffixes:
143 result_entries.append(''.join([self.result_html_prefix,
143 result_entries.append(''.join([self.result_html_prefix,
144 self.link_str % (fp,fn),
144 self.link_str % (fp,fn),
145 self.result_html_suffix]))
145 self.result_html_suffix]))
146 return '\n'.join(result_entries)
146 return '\n'.join(result_entries)
@@ -1,112 +1,97 b''
1 """Tests for IPython.lib.display.
1 """Tests for IPython.lib.display.
2
2
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012, the IPython Development Team.
5 # Copyright (c) 2012, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 from __future__ import print_function
15 from __future__ import print_function
16 from tempfile import NamedTemporaryFile, mkdtemp
16 from tempfile import NamedTemporaryFile, mkdtemp
17
17
18
18
19 # Third-party imports
19 # Third-party imports
20 import nose.tools as nt
20 import nose.tools as nt
21
21
22 # Our own imports
22 # Our own imports
23 from IPython.lib import display
23 from IPython.lib import display
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Classes and functions
26 # Classes and functions
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 #--------------------------
29 #--------------------------
30 # FileLink tests
30 # FileLink tests
31 #--------------------------
31 #--------------------------
32
32
33 def test_instantiation_FileLink():
33 def test_instantiation_FileLink():
34 """Test classes can be instantiated"""
34 """Test classes can be instantiated"""
35 fl = display.FileLink('example.txt')
35 fl = display.FileLink('example.txt')
36
36
37 def test_warning_on_non_existant_path_FileLink():
37 def test_warning_on_non_existant_path_FileLink():
38 """Calling _repr_html_ on non-existant files returns a warning"""
38 """Calling _repr_html_ on non-existant files returns a warning"""
39 fl = display.FileLink('example.txt')
39 fl = display.FileLink('example.txt')
40 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
40 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
41
41
42 def test_existing_path_FileLink():
42 def test_existing_path_FileLink():
43 """ Calling _repr_html_ functions as expected on existing filepath """
43 """ Calling _repr_html_ functions as expected on existing filepath """
44 tf = NamedTemporaryFile()
44 tf = NamedTemporaryFile()
45 fl = display.FileLink(tf.name)
45 fl = display.FileLink(tf.name)
46 actual = fl._repr_html_()
46 actual = fl._repr_html_()
47 # Note: this is a bit awkward since tf.name has to be a full path
47 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
48 # for it to exist, but that won't happen in our applications. While
49 # in practice "files/" would be prepended to the href path, os.join
50 # doesn't do that if the second value is an absolute path. So, the
51 # expected here is slightly different than what we get in practice.
52 expected = "<a href='%s' target='_blank'>%s</a><br>" % (tf.name,tf.name)
53 nt.assert_equal(actual,expected)
48 nt.assert_equal(actual,expected)
54
49
55 #--------------------------
50 #--------------------------
56 # FileLinks tests
51 # FileLinks tests
57 #--------------------------
52 #--------------------------
58
53
59 def test_instantiation_FileLinks():
54 def test_instantiation_FileLinks():
60 """Test classes can be instantiated"""
55 """Test classes can be instantiated"""
61 fls = display.FileLinks('example')
56 fls = display.FileLinks('example')
62
57
63 def test_warning_on_non_existant_path_FileLinks():
58 def test_warning_on_non_existant_path_FileLinks():
64 """Calling _repr_html_ on non-existant files returns a warning"""
59 """Calling _repr_html_ on non-existant files returns a warning"""
65 fls = display.FileLinks('example')
60 fls = display.FileLinks('example')
66 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
61 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
67
62
68 def test_existing_path_FileLinks():
63 def test_existing_path_FileLinks():
69 """ Calling _repr_html_ functions as expected on existing directory """
64 """ Calling _repr_html_ functions as expected on existing directory """
70 td = mkdtemp()
65 td = mkdtemp()
71 tf1 = NamedTemporaryFile(dir=td)
66 tf1 = NamedTemporaryFile(dir=td)
72 tf2 = NamedTemporaryFile(dir=td)
67 tf2 = NamedTemporaryFile(dir=td)
73 fl = display.FileLinks(td)
68 fl = display.FileLinks(td)
74 actual = fl._repr_html_()
69 actual = fl._repr_html_()
75 actual = actual.split('\n')
70 actual = actual.split('\n')
76 actual.sort()
71 actual.sort()
77 # Note: this is a bit awkward since tf.name has to be a full path
72 expected = ["<a href='files/%s' target='_blank'>%s</a><br>" % (tf2.name,tf2.name),
78 # for it to exist, but that won't happen in our applications. While
73 "<a href='files/%s' target='_blank'>%s</a><br>" % (tf1.name,tf1.name)]
79 # in practice "files/" would be prepended to the href path, os.join
80 # doesn't do that if the second value is an absolute path. So, the
81 # expected here is slightly different than what we get in practice.
82 expected = ["<a href='%s' target='_blank'>%s</a><br>" % (tf2.name,tf2.name.split('/')[-1]),
83 "<a href='%s' target='_blank'>%s</a><br>" % (tf1.name,tf1.name.split('/')[-1])]
84 expected.sort()
74 expected.sort()
85 # We compare the sorted list of links here as that's more reliable
75 # We compare the sorted list of links here as that's more reliable
86 nt.assert_equal(actual,expected)
76 nt.assert_equal(actual,expected)
87
77
88 #--------------------------
78 #--------------------------
89 # DirectoryLink tests
79 # DirectoryLink tests
90 #--------------------------
80 #--------------------------
91
81
92 def test_instantiation_DirectoryLink():
82 def test_instantiation_DirectoryLink():
93 """Test classes can be instantiated"""
83 """Test classes can be instantiated"""
94 dl = display.DirectoryLink('example')
84 dl = display.DirectoryLink('example')
95
85
96 def test_warning_on_non_existant_path_DirectoryLink():
86 def test_warning_on_non_existant_path_DirectoryLink():
97 """Calling _repr_html_ on non-existant files returns a warning"""
87 """Calling _repr_html_ on non-existant files returns a warning"""
98 dl = display.DirectoryLink('example')
88 dl = display.DirectoryLink('example')
99 nt.assert_true(dl._repr_html_().startswith('Path (<tt>example</tt>)'))
89 nt.assert_true(dl._repr_html_().startswith('Path (<tt>example</tt>)'))
100
90
101 def test_existing_path_FileLinks():
91 def test_existing_path_FileLinks():
102 """ Calling _repr_html_ functions as expected on existing directory """
92 """ Calling _repr_html_ functions as expected on existing directory """
103 td = mkdtemp()
93 td = mkdtemp()
104 dl = display.DirectoryLink(td)
94 dl = display.DirectoryLink(td)
105 actual = dl._repr_html_()
95 actual = dl._repr_html_()
106 # Note: this is a bit awkward since tf.name has to be a full path
96 expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (td,td)
107 # for it to exist, but that won't happen in our applications. While
108 # in practice "files/" would be prepended to the href path, os.join
109 # doesn't do that if the second value is an absolute path. So, the
110 # expected here is slightly different than what we get in practice.
111 expected = "<a href='%s' target='_blank'>%s</a><br>" % (td,td)
112 nt.assert_equal(actual,expected)
97 nt.assert_equal(actual,expected)
General Comments 0
You need to be logged in to leave comments. Login now