本文整理汇总了Python中nbconvert.exporters.HTMLExporter.from_notebook_node方法的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter.from_notebook_node方法的具体用法?Python HTMLExporter.from_notebook_node怎么用?Python HTMLExporter.from_notebook_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nbconvert.exporters.HTMLExporter
的用法示例。
在下文中一共展示了HTMLExporter.from_notebook_node方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _process
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def _process(self):
config = Config()
config.HTMLExporter.preprocessors = [CppHighlighter]
config.HTMLExporter.template_file = 'basic'
with self.attachment.file.open() as f:
notebook = nbformat.read(f, as_version=4)
html_exporter = HTMLExporter(config=config)
body, resources = html_exporter.from_notebook_node(notebook)
css_code = '\n'.join(resources['inlining'].get('css', []))
nonce = str(uuid4())
html = render_template('previewer_jupyter:ipynb_preview.html', attachment=self.attachment,
html_code=body, css_code=css_code, nonce=nonce)
response = current_app.response_class(html)
# Use CSP to restrict access to possibly malicious scripts or inline JS
csp_header = "script-src cdn.mathjax.org 'nonce-{}';".format(nonce)
response.headers['Content-Security-Policy'] = csp_header
response.headers['X-Webkit-CSP'] = csp_header
# IE10 doesn't have proper CSP support, so we need to be more strict
response.headers['X-Content-Security-Policy'] = "sandbox allow-same-origin;"
return response
示例2: _compile_string
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例3: _compile_string
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
self._req_missing_ipynb()
c = Config(self.site.config['IPYNB_CONFIG'])
c.update(get_default_jupyter_config())
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例4: compile_html_string
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def compile_html_string(self, source, is_two_file=True):
"""Export notebooks as HTML strings."""
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
with io.open(source, "r", encoding="utf8") as in_file:
nb_json = nbformat.read(in_file, current_nbformat)
(body, resources) = exportHtml.from_notebook_node(nb_json)
return body
示例5: _compile_string
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
self._req_missing_ipynb()
c = Config(self.site.config['IPYNB_CONFIG'])
c.update(get_default_jupyter_config())
if 'template_file' not in self.site.config['IPYNB_CONFIG'].get('Exporter', {}):
c['Exporter']['template_file'] = 'basic.tpl' # not a typo
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例6: main
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def main(app):
static_dir = os.path.join(app.builder.srcdir, '_static')
target_dir = os.path.join(app.builder.srcdir, 'notebooks')
source_dir = os.path.abspath(os.path.join(app.builder.srcdir,
'..', 'notebooks'))
rendered_dir = os.path.join(target_dir, 'rendered')
if not os.path.exists(static_dir):
os.makedirs(static_dir)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if not os.path.exists(rendered_dir):
os.makedirs(rendered_dir)
nbroots = []
nbtitles = []
exporter = HTMLExporter(template_file='full')
for nb_src in glob.glob(os.path.join(source_dir, '*.ipynb')):
print("converting notebook {0}".format(nb_src))
basedir, nbname = os.path.split(nb_src)
nb_dest = os.path.join(target_dir, nbname)
shutil.copyfile(nb_src, nb_dest)
with open(nb_dest, 'r') as f:
nb_json = nbformat.reads(f.read(), as_version = 4)
(body, resources) = exporter.from_notebook_node(nb_json)
root, ext = os.path.splitext(nbname)
nb_html_dest = os.path.join(rendered_dir, root + '.html')
with open(nb_html_dest, 'w') as f:
f.write(body)
nbroots.append(root)
nbtitles.append(get_notebook_title(nb_json, root))
for nbroot, nbtitle in zip(nbroots, nbtitles):
with open(os.path.join(target_dir, nbroot + '.rst'), 'w') as f:
f.write(RST_TEMPLATE.render(title=nbtitle, nbroot=nbroot))
with open(os.path.join(target_dir, 'index.rst'), 'w') as f:
f.write(INDEX_TEMPLATE.render(notebooks=nbroots,
sphinx_tag='notebook-examples'))
示例7: render
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def render(self):
try:
with open(self.file_path, 'r') as file_pointer:
notebook = nbformat.reads(file_pointer.read(), as_version=4)
except ValueError:
raise exceptions.InvalidFormat('Could not read ipython notebook file.')
exporter = HTMLExporter(config=Config({
'HTMLExporter': {
'template_file': 'basic',
},
'CSSHtmlHeaderTransformer': {
'enabled': False,
},
}))
(body, _) = exporter.from_notebook_node(notebook)
return self.TEMPLATE.render(base=self.assets_url, body=body)
示例8: render
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def render(self):
try:
with open(self.file_path, 'r') as file_pointer:
notebook = nbformat.reads(file_pointer.read(), as_version=4)
except ValueError as err:
raise exceptions.InvalidFormatError(
'Could not read ipython notebook file. {}'.format(str(err)),
extension=self.metadata.ext,
download_url=str(self.metadata.download_url),
original_exception=err,
)
exporter = HTMLExporter(config=Config({
'HTMLExporter': {
'template_file': 'basic',
},
'CSSHtmlHeaderTransformer': {
'enabled': False,
},
}))
(body, _) = exporter.from_notebook_node(notebook)
return self.TEMPLATE.render(base=self.assets_url, body=body)
示例9: notebook
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def notebook(preprocessor, tag, markup):
match = FORMAT.search(markup)
if match:
argdict = match.groupdict()
src = argdict['src']
start = argdict['start']
end = argdict['end']
language = argdict['language']
else:
raise ValueError("Error processing input, "
"expected syntax: {0}".format(SYNTAX))
if start:
start = int(start)
else:
start = 0
if end:
end = int(end)
else:
end = None
language_applied_highlighter = partial(custom_highlighter, language=language)
nb_dir = preprocessor.configs.getConfig('NOTEBOOK_DIR')
nb_path = os.path.join('content', nb_dir, src)
if not os.path.exists(nb_path):
raise ValueError("File {0} could not be found".format(nb_path))
# Create the custom notebook converter
c = Config({'CSSHTMLHeaderTransformer':
{'enabled':True, 'highlight_class':'.highlight-ipynb'},
'SubCell':
{'enabled':True, 'start':start, 'end':end}})
template_file = 'basic'
if IPYTHON_VERSION >= 3:
if os.path.exists('pelicanhtml_3.tpl'):
template_file = 'pelicanhtml_3'
elif IPYTHON_VERSION == 2:
if os.path.exists('pelicanhtml_2.tpl'):
template_file = 'pelicanhtml_2'
else:
if os.path.exists('pelicanhtml_1.tpl'):
template_file = 'pelicanhtml_1'
if IPYTHON_VERSION >= 2:
subcell_kwarg = dict(preprocessors=[SubCell])
else:
subcell_kwarg = dict(transformers=[SubCell])
exporter = HTMLExporter(config=c,
template_file=template_file,
filters={'highlight2html': language_applied_highlighter},
**subcell_kwarg)
# read and parse the notebook
with open(nb_path, encoding="utf-8") as f:
nb_text = f.read()
if IPYTHON_VERSION < 3:
nb_json = IPython.nbformat.current.reads_json(nb_text)
else:
try:
nb_json = nbformat.reads(nb_text, as_version=4)
except:
nb_json = IPython.nbformat.reads(nb_text, as_version=4)
(body, resources) = exporter.from_notebook_node(nb_json)
# if we haven't already saved the header, save it here.
if not notebook.header_saved:
print ("\n ** Writing styles to _nb_header.html: "
"this should be included in the theme. **\n")
header = '\n'.join(CSS_WRAPPER.format(css_line)
for css_line in resources['inlining']['css'])
header += JS_INCLUDE
with open('_nb_header.html', 'w', encoding="utf-8") as f:
f.write(header)
notebook.header_saved = True
# this will stash special characters so that they won't be transformed
# by subsequent processes.
body = preprocessor.configs.htmlStash.store(body, safe=True)
return body
示例10: get
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def get(self, prepath, user, filename):
## filename can have a path on it
next = "/%s/hub/%s/public/%s" % (prepath, user, filename)
filesystem_path = "/home/%s/public_html/%s" % (user, filename)
if os.path.isfile(filesystem_path): # download, raw, or view notebook
command = "view"
if len(self.get_arguments("view")) > 0:
command = "view"
elif len(self.get_arguments("download")) > 0:
command = "download"
elif len(self.get_arguments("copy")) > 0:
command = "copy"
elif len(self.get_arguments("pdf")) > 0:
command = "pdf"
elif len(self.get_arguments("raw")) > 0:
command = "raw"
# else: view
if filename.endswith(".ipynb"):
if command in ["view", "pdf"]:
# first, make a notebook html:
#with open("/home/%s/public_html/%s" % (user, filename)) as fp:
# notebook_content = fp.read()
if command == "view":
exporter = HTMLExporter(template_file='full-tabs')
else:
exporter = PDFExporter(latex_count=1)
nb_json = nbformat.read("/home/%s/public_html/%s" % (user, filename), as_version=4)
#if command == "pdf":
# # If pdf, remove heading numbering:
# for cell in nb_json["worksheets"][0]["cells"]:
# if cell["cell_type"] == "heading":
# cell["source"] = re.sub("^([0-9]+\.?)+\s", "", cell["source"])
# where to get css, images?
if command == "pdf":
self.set_header('Content-Type', "application/pdf")
base_filename = os.path.basename(filename)
self.set_header('Content-Disposition', 'attachment; filename="%s"' % base_filename)
else: # render as HTML
# add header/footer:
path = "/%s/hub/%s/public" % (prepath, user)
parts = [(path, path)]
for part in filename.split("/")[:-1]:
path += "/" + part
parts.append((path, part))
breadcrumbs = " / ".join(map(lambda pair: '<a href="%s" target="_blank">%s</a>' % pair, parts))
env = {
"breadcrumbs": breadcrumbs,
"url": "https://athena.brynmawr.edu/" + next + "?download"
}
cell = new_markdown_cell(source="""<table width="100%" style="border: none;">
<tr style="border: none;">
<td style="border: none;" width="100px">
<img src="https://blog.jupyter.org/content/images/2015/02/jupyter-sq-text.png" width="100"/>
</td>
<td style="border: none;" width="50%">
<h2><a href="https://athena.brynmawr.edu/">Jupyter at Bryn Mawr College</a></h2>
</td>
<td style="border: none;">
<a href="https://athena.brynmawr.edu/jupyter/hub/dblank/public/Jupyter%20Help.ipynb" title="Help">
<span class="fa fa-info-circle fa-2x menu-icon"></span>
<span class="menu-text">Help</span>
</a>
</td>
<td style="border: none;">
<a href="{url}" title="Download Notebook" download>
<span class="fa fa-download fa-2x menu-icon"></span>
<span class="menu-text">Download Notebook</span>
</a>
</td>
</tr>
<tr style="border: none;">
<td colspan="4" style="border: none;">
<b>Public notebooks:</b> {breadcrumbs}
</td>
</tr>
</table>""".format(**env))
nb_json["cells"].insert(0, cell)
(body, resources) = exporter.from_notebook_node(nb_json)
self.write(body)
elif command == "download": # download notebook json
self.download(user, filename, "text/plain")
elif command == "copy": # copy notebook json, if logged in
if self.get_current_user_name():
self.copy_file(user, filename, self.get_current_user_name())
else:
self.write("Please <a href=\"/%s/hub/login?next=%s\">login</a> to allow copy." % (prepath, next))
else: # raw, just get file contents
with open("/home/%s/public_html/%s" % (user, filename), "rb") as fp:
self.write(fp.read())
else: # some other kind of file
# FIXME: how to get all of custom stuff?
if command == "copy":
if self.get_current_user_name():
self.copy_file(user, filename, self.get_current_user_name())
else:
self.write("Please <a href=\"/%s/hub/login?next=%s\">login</a> to allow copy." % (prepath, next))
else: # whatever, just get or download it
base_filename = os.path.basename(filename)
base, ext = os.path.splitext(base_filename)
#.........这里部分代码省略.........
示例11: notebook
# 需要导入模块: from nbconvert.exporters import HTMLExporter [as 别名]
# 或者: from nbconvert.exporters.HTMLExporter import from_notebook_node [as 别名]
def notebook(preprocessor, tag, markup):
match = FORMAT.search(markup)
if match:
argdict = match.groupdict()
src = argdict["src"]
start = argdict["start"]
end = argdict["end"]
language = argdict["language"]
else:
raise ValueError("Error processing input, " "expected syntax: {0}".format(SYNTAX))
if start:
start = int(start)
else:
start = 0
if end:
end = int(end)
else:
end = None
language_applied_highlighter = partial(custom_highlighter, language=language)
nb_dir = preprocessor.configs.getConfig("NOTEBOOK_DIR")
nb_path = os.path.join("content", nb_dir, src)
if not os.path.exists(nb_path):
raise ValueError("File {0} could not be found".format(nb_path))
# Create the custom notebook converter
c = Config(
{
"CSSHTMLHeaderTransformer": {"enabled": True, "highlight_class": ".highlight-ipynb"},
"SubCell": {"enabled": True, "start": start, "end": end},
}
)
template_file = "basic"
if IPYTHON_VERSION >= 3:
if os.path.exists("pelicanhtml_3.tpl"):
template_file = "pelicanhtml_3"
elif IPYTHON_VERSION == 2:
if os.path.exists("pelicanhtml_2.tpl"):
template_file = "pelicanhtml_2"
else:
if os.path.exists("pelicanhtml_1.tpl"):
template_file = "pelicanhtml_1"
if IPYTHON_VERSION >= 2:
subcell_kwarg = dict(preprocessors=[SubCell])
else:
subcell_kwarg = dict(transformers=[SubCell])
exporter = HTMLExporter(
config=c, template_file=template_file, filters={"highlight2html": language_applied_highlighter}, **subcell_kwarg
)
# read and parse the notebook
with open(nb_path) as f:
nb_text = f.read()
if IPYTHON_VERSION < 3:
nb_json = IPython.nbformat.current.reads_json(nb_text)
else:
try:
nb_json = nbformat.reads(nb_text, as_version=4)
except:
nb_json = IPython.nbformat.reads(nb_text, as_version=4)
(body, resources) = exporter.from_notebook_node(nb_json)
# if we haven't already saved the header, save it here.
if not notebook.header_saved:
print("\n ** Writing styles to _nb_header.html: " "this should be included in the theme. **\n")
header = "\n".join(CSS_WRAPPER.format(css_line) for css_line in resources["inlining"]["css"])
header += JS_INCLUDE
with open("_nb_header.html", "w") as f:
f.write(header)
notebook.header_saved = True
# this will stash special characters so that they won't be transformed
# by subsequent processes.
body = preprocessor.configs.htmlStash.store(body, safe=True)
return body