How to use the notebook.base.handlers.IPythonHandler function in notebook

To help you get started, we’ve selected a few notebook examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyter / notebook / notebook / base / handlers.py View on Github external
self.finish(json.dumps({"version":notebook.__version__}))


class TrailingSlashHandler(web.RequestHandler):
    """Simple redirect handler that strips trailing slashes
    
    This should be the first, highest priority handler.
    """
    
    def get(self):
        self.redirect(self.request.uri.rstrip('/'))
    
    post = put = get


class FilesRedirectHandler(IPythonHandler):
    """Handler for redirecting relative URLs to the /files/ handler"""
    
    @staticmethod
    def redirect_to_files(self, path):
        """make redirect logic a reusable static method
        
        so it can be called from other handlers.
        """
        cm = self.contents_manager
        if cm.dir_exists(path):
            # it's a *directory*, redirect to /tree
            url = url_path_join(self.base_url, 'tree', url_escape(path))
        else:
            orig_path = path
            # otherwise, redirect to /files
            parts = path.split('/')
github jupyterhub / nbgitpuller / nbgitpuller / handlers.py View on Github external
self.emit({'phase': 'finished'})
        except Exception as e:
            self.emit({
                'phase': 'error',
                'message': str(e),
                'output': '\n'.join([
                    l.strip()
                    for l in traceback.format_exception(
                        type(e), e, e.__traceback__
                    )
                ])
            })
        finally:
            self.git_lock.release()

class UIHandler(IPythonHandler):
    def initialize(self):
        super().initialize()
        # FIXME: Is this really the best way to use jinja2 here?
        # I can't seem to get the jinja2 env in the base handler to
        # actually load templates from arbitrary paths ugh.
        jinja2_env = self.settings['jinja2_env']
        jinja2_env.loader = jinja2.ChoiceLoader([
            jinja2_env.loader,
            jinja2.FileSystemLoader(
                os.path.join(os.path.dirname(__file__), 'templates')
            )
        ])

    @web.authenticated
    @gen.coroutine
    def get(self):
github jupyter / nbdime / nbdime / webapp / nbdimeserver.py View on Github external
# TODO: See /notebook/services/contents/handlers.py for possibly useful utilities:
#contents_manager
#ContentsHandler


# Separate logger for server entrypoint (?)
_logger = logging.getLogger(__name__)


here = os.path.abspath(os.path.dirname(__file__))
static_path = os.path.join(here, 'static')
template_path = os.path.join(here, 'templates')


class NbdimeHandler(IPythonHandler):
    def initialize(self, **params):
        self.params = params

    def base_args(self):
        fn = self.params.get('outputfilename', None)
        base = {
            'closable': self.params.get('closable', False),
            'savable': fn is not None,
            'baseUrl': self.nbdime_base_url,
            'hideUnchanged': self.params.get('hide_unchanged', True),
            'mathjaxUrl': self.mathjax_url,
            'mathjaxConfig': self.mathjax_config,
        }
        if fn:
            # For reference, e.g. if user wants to download file
            base['outputfilename'] = fn
github StochSS / stochss / stochss / handlers / pages.py View on Github external
import os
from tornado import web
from notebook.base.handlers import IPythonHandler
import logging

log = logging.getLogger('stochss')

class PageHandler(IPythonHandler):
  '''
  Base handler for rendering stochss pages.
  '''
  def get_template_path(self):
    '''
    Retrieve the location of stochss pages output by webpack.
    The html pages are located in the same directory as static assets.
    '''
    return self.settings['config']['NotebookApp']['extra_static_paths'][0]

  def get_server_path(self):
    try:
        server_path = os.environ['JUPYTERHUB_SERVICE_PREFIX']
    except:
        server_path = '/'
github jupyterlab / jupyterlab / packages / services / examples / browser-require / main.py View on Github external
"""
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
"""
from notebook.notebookapp import NotebookApp
import os
from jinja2 import FileSystemLoader
from notebook.base.handlers import IPythonHandler, FileFindHandler
from traitlets import Unicode


HERE = os.path.dirname(__file__)
LOADER = FileSystemLoader(HERE)


class ExampleHander(IPythonHandler):
    """Handle requests between the main app page and notebook server."""

    def get(self):
        """Get the main page for the application's interface."""
        return self.write(self.render_template('index.html',
                                               static=self.static_url,
                                               base_url=self.base_url,
                                               token=self.settings['token']))

    def get_template(self, name):
        return LOADER.load(self.settings['jinja2_env'], name)


class ExampleApp(NotebookApp):
    """A notebook app that runs the example."""
github jupyterhub / jupyter-server-proxy / jupyter_server_proxy / api.py View on Github external
'launcher_entry': {
                    'enabled': sp.launcher_entry.enabled,
                    'title': sp.launcher_entry.title
                }
            }
            if sp.launcher_entry.icon_path:
                icon_url = ujoin(self.base_url, 'server-proxy', 'icon', sp.name)
                item['launcher_entry']['icon_url'] = icon_url

            data.append(item)

        self.write({'server_processes': data})


# FIXME: Should be a StaticFileHandler subclass
class IconHandler(IPythonHandler):
    """
    Serve launcher icons
    """
    def initialize(self, icons):
        """
        icons is a dict of titles to paths
        """
        self.icons = icons

    async def get(self, name):
        if name not in self.icons:
            raise web.HTTPError(404)
        path = self.icons[name]

        # Guess mimetype appropriately
        # Stolen from https://github.com/tornadoweb/tornado/blob/b399a9d19c45951e4561e6e580d7e8cf396ef9ff/tornado/web.py#L2881
github dalejung / nbx / nbx / handlers / __init__.py View on Github external
handlers.extend(load_handlers(mname))
            except:
                # TODO what to on error?
                raise
        # note that the base init_handlers has a 404 catch all
        # it needs to always be last
        handlers.extend(old_init_handlers(self, settings))
        return handlers

    NotebookWebApplication.init_handlers = init_handlers


template_path = os.path.join(os.path.dirname(__file__), "templates")
env = Environment(loader=FileSystemLoader(template_path))

class NBXHandler(IPythonHandler):
    def get_template(self, name):
        """Return the jinja template object for a given name"""
        try:
            template = env.get_template(name)
        except:
            template = IPythonHandler.get_template(self, name)
        return template
github yuvipanda / nbresuse / nbresuse / api.py View on Github external
import json
from concurrent.futures import ThreadPoolExecutor

import psutil
from notebook.base.handlers import IPythonHandler
from tornado import web
from tornado.concurrent import run_on_executor

try:
    # Traitlets >= 4.3.3
    from traitlets import Callable
except ImportError:
    from .utils import Callable


class ApiHandler(IPythonHandler):

    executor = ThreadPoolExecutor(max_workers=5)

    @web.authenticated
    async def get(self):
        """
        Calculate and return current resource usage metrics
        """
        config = self.settings["nbresuse_display_config"]

        cur_process = psutil.Process()
        all_processes = [cur_process] + cur_process.children(recursive=True)

        # Get memory information
        rss = sum([p.memory_info().rss for p in all_processes])
github funkey / nyroglancer / nyroglancer / ndstore.py View on Github external
def get(self, data_format, token, scale_key, min_x, max_x, min_y, max_y, min_z, max_z):

        client = get_kernel_client(token)

        if client is None:
            raise HTTPError(404)

        expression = "nyroglancer.ndstore.Data.backend(nyroglancer.volumes['%s'], \"%s\", \"%s\", %s, %s, %s, %s, %s, %s)" % (token, scale_key, data_format, min_x, max_x, min_y, max_y, min_z, max_z)
        ascii_data = evaluate(client, expression)
        data = binascii.a2b_base64(ascii_data)
        self.write(data)
        self.set_header("Content-Type", Data.content_type[data_format])
        self.set_header("Content-Length", len(data))
        self.set_header("Access-Control-Allow-Origin", "*")

class RegisterToken(IPythonHandler):

    def get(self, token, connection_file):

        register_connection_file(token, url_unescape(connection_file))
github timkpaine / knowledgelab / knowledgelab / extension.py View on Github external
import ujson
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
from .commands import nb_to_kp


class SubmitKnowledgeHandler(IPythonHandler):
    def get(self):
        notebook = self.get_argument('notebook', 'error')
        self.finish(notebook)


class KnowledgePostHandler(IPythonHandler):
    def post(self):
        if not self.request.body:
            self.set_status(401)
            self.finish('error')
            return

        json = ujson.loads(self.request.body)
        print(json)

        if 'path' not in json:
            self.set_status(401)
            self.finish('error')
            return

        path = json.pop('path')
        if not path or not json.get('title', None) or not json.get('authors', None) or not json.get('tags', None) or not json.get('tldr', None):