##// END OF EJS Templates
Add IPython Notebook exporter
Julia Evans -
Show More
@@ -0,0 +1,36 b''
1 """IPython Notebook Exporter class"""
2
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
14
15 from .exporter import Exporter
16 from IPython.nbformat import current as nbformat
17
18 #-----------------------------------------------------------------------------
19 # Classes
20 #-----------------------------------------------------------------------------
21
22 class NotebookExporter(Exporter):
23 """
24 Exports an IPython notebook.
25 """
26 def _file_extension_default(self):
27 return 'ipynb'
28
29 output_mimetype = 'application/json'
30
31 def from_notebook_node(self, nb, resources=None, **kw):
32 nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
33 output = nbformat.writes_json(nb_copy)
34 return output, resources
35
36
@@ -0,0 +1,45 b''
1 """
2 Module with tests for notebook.py
3 """
4
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
7 #
8 # Distributed under the terms of the Modified BSD License.
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 from .base import ExportersTestsBase
18 from ..notebook import NotebookExporter
19
20 #-----------------------------------------------------------------------------
21 # Class
22 #-----------------------------------------------------------------------------
23
24 class TestNotebookExporter(ExportersTestsBase):
25 """Contains test functions for notebook.py"""
26
27 exporter_class = NotebookExporter
28
29 def test_constructor(self):
30 """
31 Can a NotebookExporter be constructed?
32 """
33 NotebookExporter()
34
35
36 def test_export(self):
37 """
38 Does the NotebookExporter return the file unchanged?
39 """
40 with open(self._get_notebook()) as f:
41 file_contents = f.read()
42 (output, resources) = NotebookExporter().from_filename(self._get_notebook())
43 assert len(output) > 0
44 assert output == file_contents
45
@@ -1,172 +1,174 b''
1 """Module containing single call export functions."""
1 """Module containing single call export functions."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from functools import wraps
6 from functools import wraps
7
7
8 from IPython.nbformat.v3.nbbase import NotebookNode
8 from IPython.nbformat.v3.nbbase import NotebookNode
9 from IPython.utils.decorators import undoc
9 from IPython.utils.decorators import undoc
10 from IPython.utils.py3compat import string_types
10 from IPython.utils.py3compat import string_types
11
11
12 from .exporter import Exporter
12 from .exporter import Exporter
13 from .templateexporter import TemplateExporter
13 from .templateexporter import TemplateExporter
14 from .html import HTMLExporter
14 from .html import HTMLExporter
15 from .slides import SlidesExporter
15 from .slides import SlidesExporter
16 from .latex import LatexExporter
16 from .latex import LatexExporter
17 from .pdf import PDFExporter
17 from .pdf import PDFExporter
18 from .markdown import MarkdownExporter
18 from .markdown import MarkdownExporter
19 from .python import PythonExporter
19 from .python import PythonExporter
20 from .rst import RSTExporter
20 from .rst import RSTExporter
21 from .notebook import NotebookExporter
21
22
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
23 # Classes
24 # Classes
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25
26
26 @undoc
27 @undoc
27 def DocDecorator(f):
28 def DocDecorator(f):
28
29
29 #Set docstring of function
30 #Set docstring of function
30 f.__doc__ = f.__doc__ + """
31 f.__doc__ = f.__doc__ + """
31 nb : :class:`~{nbnode_mod}.NotebookNode`
32 nb : :class:`~{nbnode_mod}.NotebookNode`
32 The notebook to export.
33 The notebook to export.
33 config : config (optional, keyword arg)
34 config : config (optional, keyword arg)
34 User configuration instance.
35 User configuration instance.
35 resources : dict (optional, keyword arg)
36 resources : dict (optional, keyword arg)
36 Resources used in the conversion process.
37 Resources used in the conversion process.
37
38
38 Returns
39 Returns
39 -------
40 -------
40 tuple- output, resources, exporter_instance
41 tuple- output, resources, exporter_instance
41 output : str
42 output : str
42 Jinja 2 output. This is the resulting converted notebook.
43 Jinja 2 output. This is the resulting converted notebook.
43 resources : dictionary
44 resources : dictionary
44 Dictionary of resources used prior to and during the conversion
45 Dictionary of resources used prior to and during the conversion
45 process.
46 process.
46 exporter_instance : Exporter
47 exporter_instance : Exporter
47 Instance of the Exporter class used to export the document. Useful
48 Instance of the Exporter class used to export the document. Useful
48 to caller because it provides a 'file_extension' property which
49 to caller because it provides a 'file_extension' property which
49 specifies what extension the output should be saved as.
50 specifies what extension the output should be saved as.
50
51
51 Notes
52 Notes
52 -----
53 -----
53 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT
54 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT
54 """.format(nbnode_mod=NotebookNode.__module__)
55 """.format(nbnode_mod=NotebookNode.__module__)
55
56
56 @wraps(f)
57 @wraps(f)
57 def decorator(*args, **kwargs):
58 def decorator(*args, **kwargs):
58 return f(*args, **kwargs)
59 return f(*args, **kwargs)
59
60
60 return decorator
61 return decorator
61
62
62
63
63 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
64 # Functions
65 # Functions
65 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
66
67
67 __all__ = [
68 __all__ = [
68 'export',
69 'export',
69 'export_html',
70 'export_html',
70 'export_custom',
71 'export_custom',
71 'export_slides',
72 'export_slides',
72 'export_latex',
73 'export_latex',
73 'export_pdf',
74 'export_pdf',
74 'export_markdown',
75 'export_markdown',
75 'export_python',
76 'export_python',
76 'export_rst',
77 'export_rst',
77 'export_by_name',
78 'export_by_name',
78 'get_export_names',
79 'get_export_names',
79 'ExporterNameError'
80 'ExporterNameError'
80 ]
81 ]
81
82
82
83
83 class ExporterNameError(NameError):
84 class ExporterNameError(NameError):
84 pass
85 pass
85
86
86 @DocDecorator
87 @DocDecorator
87 def export(exporter, nb, **kw):
88 def export(exporter, nb, **kw):
88 """
89 """
89 Export a notebook object using specific exporter class.
90 Export a notebook object using specific exporter class.
90
91
91 Parameters
92 Parameters
92 ----------
93 ----------
93 exporter : class:`~IPython.nbconvert.exporters.exporter.Exporter` class or instance
94 exporter : class:`~IPython.nbconvert.exporters.exporter.Exporter` class or instance
94 Class type or instance of the exporter that should be used. If the
95 Class type or instance of the exporter that should be used. If the
95 method initializes it's own instance of the class, it is ASSUMED that
96 method initializes it's own instance of the class, it is ASSUMED that
96 the class type provided exposes a constructor (``__init__``) with the same
97 the class type provided exposes a constructor (``__init__``) with the same
97 signature as the base Exporter class.
98 signature as the base Exporter class.
98 """
99 """
99
100
100 #Check arguments
101 #Check arguments
101 if exporter is None:
102 if exporter is None:
102 raise TypeError("Exporter is None")
103 raise TypeError("Exporter is None")
103 elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
104 elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
104 raise TypeError("exporter does not inherit from Exporter (base)")
105 raise TypeError("exporter does not inherit from Exporter (base)")
105 if nb is None:
106 if nb is None:
106 raise TypeError("nb is None")
107 raise TypeError("nb is None")
107
108
108 #Create the exporter
109 #Create the exporter
109 resources = kw.pop('resources', None)
110 resources = kw.pop('resources', None)
110 if isinstance(exporter, Exporter):
111 if isinstance(exporter, Exporter):
111 exporter_instance = exporter
112 exporter_instance = exporter
112 else:
113 else:
113 exporter_instance = exporter(**kw)
114 exporter_instance = exporter(**kw)
114
115
115 #Try to convert the notebook using the appropriate conversion function.
116 #Try to convert the notebook using the appropriate conversion function.
116 if isinstance(nb, NotebookNode):
117 if isinstance(nb, NotebookNode):
117 output, resources = exporter_instance.from_notebook_node(nb, resources)
118 output, resources = exporter_instance.from_notebook_node(nb, resources)
118 elif isinstance(nb, string_types):
119 elif isinstance(nb, string_types):
119 output, resources = exporter_instance.from_filename(nb, resources)
120 output, resources = exporter_instance.from_filename(nb, resources)
120 else:
121 else:
121 output, resources = exporter_instance.from_file(nb, resources)
122 output, resources = exporter_instance.from_file(nb, resources)
122 return output, resources
123 return output, resources
123
124
124 exporter_map = dict(
125 exporter_map = dict(
125 custom=TemplateExporter,
126 custom=TemplateExporter,
126 html=HTMLExporter,
127 html=HTMLExporter,
127 slides=SlidesExporter,
128 slides=SlidesExporter,
128 latex=LatexExporter,
129 latex=LatexExporter,
129 pdf=PDFExporter,
130 pdf=PDFExporter,
130 markdown=MarkdownExporter,
131 markdown=MarkdownExporter,
131 python=PythonExporter,
132 python=PythonExporter,
132 rst=RSTExporter,
133 rst=RSTExporter,
134 notebook=NotebookExporter,
133 )
135 )
134
136
135 def _make_exporter(name, E):
137 def _make_exporter(name, E):
136 """make an export_foo function from a short key and Exporter class E"""
138 """make an export_foo function from a short key and Exporter class E"""
137 def _export(nb, **kw):
139 def _export(nb, **kw):
138 return export(E, nb, **kw)
140 return export(E, nb, **kw)
139 _export.__doc__ = """Export a notebook object to {0} format""".format(name)
141 _export.__doc__ = """Export a notebook object to {0} format""".format(name)
140 return _export
142 return _export
141
143
142 g = globals()
144 g = globals()
143
145
144 for name, E in exporter_map.items():
146 for name, E in exporter_map.items():
145 g['export_%s' % name] = DocDecorator(_make_exporter(name, E))
147 g['export_%s' % name] = DocDecorator(_make_exporter(name, E))
146
148
147 @DocDecorator
149 @DocDecorator
148 def export_by_name(format_name, nb, **kw):
150 def export_by_name(format_name, nb, **kw):
149 """
151 """
150 Export a notebook object to a template type by its name. Reflection
152 Export a notebook object to a template type by its name. Reflection
151 (Inspect) is used to find the template's corresponding explicit export
153 (Inspect) is used to find the template's corresponding explicit export
152 method defined in this module. That method is then called directly.
154 method defined in this module. That method is then called directly.
153
155
154 Parameters
156 Parameters
155 ----------
157 ----------
156 format_name : str
158 format_name : str
157 Name of the template style to export to.
159 Name of the template style to export to.
158 """
160 """
159
161
160 function_name = "export_" + format_name.lower()
162 function_name = "export_" + format_name.lower()
161
163
162 if function_name in globals():
164 if function_name in globals():
163 return globals()[function_name](nb, **kw)
165 return globals()[function_name](nb, **kw)
164 else:
166 else:
165 raise ExporterNameError("template for `%s` not found" % function_name)
167 raise ExporterNameError("template for `%s` not found" % function_name)
166
168
167
169
168 def get_export_names():
170 def get_export_names():
169 """Return a list of the currently supported export targets
171 """Return a list of the currently supported export targets
170
172
171 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT"""
173 WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT"""
172 return sorted(exporter_map.keys())
174 return sorted(exporter_map.keys())
General Comments 0
You need to be logged in to leave comments. Login now