From abe28bc4fe5d3e026c68c01248047656f58db635 Mon Sep 17 00:00:00 2001 From: Rosio Date: Wed, 11 Sep 2024 11:03:54 -0700 Subject: [PATCH] Add `view` handler to serve files when Notebook 7 is installed (#287) * serve files from nbclassic when notebook 7 is installed * update handler comment --- nbclassic/notebookapp.py | 1 + nbclassic/view/__init__.py | 1 + nbclassic/view/handlers.py | 40 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 nbclassic/view/__init__.py create mode 100644 nbclassic/view/handlers.py diff --git a/nbclassic/notebookapp.py b/nbclassic/notebookapp.py index bcf947eba..e80130b70 100644 --- a/nbclassic/notebookapp.py +++ b/nbclassic/notebookapp.py @@ -280,6 +280,7 @@ def initialize_handlers(self): handlers.extend(load_handlers('nbclassic.tree.handlers')) handlers.extend(load_handlers('nbclassic.notebook.handlers')) handlers.extend(load_handlers('nbclassic.edit.handlers')) + handlers.extend(load_handlers('nbclassic.view.handlers')) self.handlers.extend(handlers) # Wildcard routes diff --git a/nbclassic/view/__init__.py b/nbclassic/view/__init__.py new file mode 100644 index 000000000..6e91c4e16 --- /dev/null +++ b/nbclassic/view/__init__.py @@ -0,0 +1 @@ +"""Tornado handlers for viewing HTML files.""" \ No newline at end of file diff --git a/nbclassic/view/handlers.py b/nbclassic/view/handlers.py new file mode 100644 index 000000000..46c71e51d --- /dev/null +++ b/nbclassic/view/handlers.py @@ -0,0 +1,40 @@ +#encoding: utf-8 +"""Tornado handlers for viewing HTML files.""" + +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. + +from tornado import web, gen + + +from jupyter_server.base.handlers import JupyterHandler, path_regex +from jupyter_server.utils import url_escape, ensure_async, url_path_join + +from nbclassic import nbclassic_path + + +class CustomViewHandler(JupyterHandler): + """Render HTML files within an iframe.""" + + @web.authenticated + @gen.coroutine + def get(self, path): + """Get a view on a given path.""" + + path = path.strip('/') + exists = yield ensure_async(self.contents_manager.file_exists(path)) + if not exists: + raise web.HTTPError(404, u'File does not exist: %s' % path) + + basename = path.rsplit('/', 1)[-1] + file_url = url_path_join(self.base_url, "files", url_escape(path)) + self.write(self.render_template('view.html', + file_url=file_url, + page_title=basename, + ) + ) + + +default_handlers = [ + (r"{}/view{}".format(nbclassic_path(), path_regex), CustomViewHandler), +] \ No newline at end of file