Skip to main content
`Ctrl`+`K`

# jupyter_server.base package

## Submodules

Provides access to variables pertaining to specific call contexts.

class jupyter_server.base.call_context.CallContext

  Bases: `object`

  CallContext essentially acts as a namespace for managing context variables.

  Although not required, it is recommended that any “file-spanning” context variable names (i.e., variables that will be set or retrieved from multiple files or services) be added as constants to this class definition.

  JUPYTER_HANDLER: `str` = 'JUPYTER_HANDLER'

    Provides access to the current request handler once set.

  classmethod context_variable_names()

    Returns a list of variable names set for this call context.

    Returns:

      names – A list of variable names set for this call context.

    Return type:

      List[str]

  classmethod get(name)

    Returns the value corresponding the named variable relative to this context.

    If the named variable doesn’t exist, None will be returned.

    Parameters:

      name (str) – The name of the variable to get from the call context

    Returns:

      value – The value associated with the named variable for this call context

    Return type:

      Any

  classmethod set(name, value)

    Sets the named variable to the specified value in the current call context.

    Parameters:

      - name (str) – The name of the variable to store into the call context

      - value (Any) – The value of the variable to store into the call context

    Return type:

      None

Base Tornado handlers for the Jupyter server.

class jupyter_server.base.handlers.APIHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  Base class for API handlers

  property content_security_policy: str

    The default Content-Security-Policy header

    Can be overridden by defining Content-Security-Policy in settings[‘headers’]

  finish(*args, **kwargs)

    Finish an API response.

    Return type:

      `Future`[`Any`]

  get_login_url()

    Get the login url.

    Return type:

      `str`

  options(*args, **kwargs)

    Get the options.

    Return type:

      `None`

  async prepare()

    Prepare an API response.

    Return type:

      `None`

  update_api_activity()

    Update last_activity of API requests

    Return type:

      `None`

  write_error(status_code, **kwargs)

    APIHandler errors are JSON, not human pages

    Return type:

      `None`

class jupyter_server.base.handlers.APIVersionHandler(application, request, **kwargs)

  Bases: `APIHandler`

  An API handler for the server version.

  get()

    Get the server version info.

    Return type:

      `None`

class jupyter_server.base.handlers.AuthenticatedFileHandler(application, request, **kwargs)

  Bases: `JupyterHandler`, `StaticFileHandler`

  static files should only be accessible when logged in

  auth_resource = 'contents'
  compute_etag()

    Compute the etag.

    Return type:

      `str` | `None`

  property content_security_policy: str

    The default Content-Security-Policy header

    Can be overridden by defining Content-Security-Policy in settings[‘headers’]

  get(path, **kwargs)

    Get a file by path.

    Return type:

      `Awaitable`[`None`]

  get_content_type()

    Get the content type.

    Return type:

      `str`

  head(path)

    Get the head response for a path.

    Return type:

      `Awaitable`[`None`]

  set_headers()

    Set the headers.

    Return type:

      `None`

  validate_absolute_path(root, absolute_path)

    Validate and return the absolute path.

    Requires tornado 3.1

    Adding to tornado’s own handling, forbids the serving of hidden files.

    Return type:

      `str`

class jupyter_server.base.handlers.AuthenticatedHandler(application, request, **kwargs)

  Bases: `RequestHandler`

  A RequestHandler with an authenticated user.

  property authorizer: Authorizer
  property base_url: str
  clear_login_cookie()

    Clear a login cookie.

    Return type:

      `None`

  property content_security_policy: str

    The default Content-Security-Policy header

    Can be overridden by defining Content-Security-Policy in settings[‘headers’]

  property cookie_name: str
  force_clear_cookie(name, path='/', domain=None)

    Force a cookie clear.

    Return type:

      `None`

  get_current_user()

    Get the current user.

    Return type:

      `str`

  property identity_provider: IdentityProvider
  property logged_in: bool

    Is a user currently logged in?

  property login_available: bool

    May a user proceed to log in?

    This returns True if login capability is available, irrespective of whether the user is already logged in or not.

  property login_handler: Any

    Return the login handler for this application, if any.

  set_default_headers()

    Set the default headers.

    Return type:

      `None`

  skip_check_origin()

    Ask my login_handler if I should skip the origin_check

    For example: in the default LoginHandler, if a request is token-authenticated, origin checking should be skipped.

    Return type:

      `bool`

  property token: str | None

    Return the login token for this application, if any.

  property token_authenticated: bool

    Have I been authenticated with a token?

class jupyter_server.base.handlers.FileFindHandler(application, request, **kwargs)

  Bases: `JupyterHandler`, `StaticFileHandler`

  subclass of StaticFileHandler for serving files from a search path

  The setting “static_immutable_cache” can be set up to serve some static file as immutable (e.g. file name containing a hash). The setting is a list of base URL, every static file URL starting with one of those will be immutable.

  compute_etag()

    Compute the etag.

    Return type:

      `str` | `None`

  get(path, include_body=True)
    Return type:

      `Coroutine`[`Any`, `Any`, `None`]

  classmethod get_absolute_path(roots, path)

    locate a file to serve on our static file search path

    Return type:

      `str`

  head(path)
    Return type:

      `Awaitable`[`None`]

  initialize(path, default_filename=None, no_cache_paths=None)

    Initialize the file find handler.

    Return type:

      `None`

  root: tuple[str]
  set_headers()

    Set the headers.

    Return type:

      `None`

  validate_absolute_path(root, absolute_path)

    check if the file should be served (raises 404, 403, etc.)

    Return type:

      `str` | `None`

class jupyter_server.base.handlers.FilesRedirectHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  Handler for redirecting relative URLs to the /files/ handler

  get(path='')
    Return type:

      `None`

  async static redirect_to_files(self, path)

    make redirect logic a reusable static method

    so it can be called from other handlers.

    Return type:

      `None`

class jupyter_server.base.handlers.JupyterHandler(application, request, **kwargs)

  Bases: `AuthenticatedHandler`

  Jupyter-specific extensions to authenticated handling

  Mostly property shortcuts to Jupyter-specific settings.

  property allow_credentials: bool

    Whether to set Access-Control-Allow-Credentials

  property allow_origin: str

    Normal Access-Control-Allow-Origin

  property allow_origin_pat: str | None

    Regular expression version of allow_origin

  check_host()

    Check the host header if remote access disallowed.

    Returns True if the request should continue, False otherwise.

    Return type:

      `bool`

  check_origin(origin_to_satisfy_tornado='')

    Check Origin for cross-site API requests, including websockets

    Copied from WebSocket with changes:

    - allow unspecified host/origin (e.g. scripts)

    - allow token-authenticated requests

    Return type:

      `bool`

  check_referer()

    Check Referer for cross-site requests. Disables requests to certain endpoints with external or missing Referer. If set, allow_origin settings are applied to the Referer to whitelist specific cross-origin sites. Used on GET for api endpoints and /files/ to block cross-site inclusion (XSSI).

    Return type:

      `bool`

  check_xsrf_cookie()

    Bypass xsrf cookie checks when token-authenticated

    Return type:

      `None`

  property config: dict[str, Any] | None
  property config_manager: ConfigManager
  property contents_js_source: str
  property contents_manager: ContentsManager
  property default_url: str
  property event_logger: EventLogger
  get_json_body()

    Return the body of the request as JSON data.

    Return type:

      `dict`[`str`, `Any`] | `None`

  get_origin()
    Return type:

      `str` | `None`

  get_template(name)

    Return the jinja template object for a given name

  property jinja_template_vars: dict[str, Any]

    User-supplied values to supply to jinja templates.

  property kernel_manager: AsyncMappingKernelManager
  property kernel_spec_manager: KernelSpecManager
  property log: Logger

    use the Jupyter log by default, falling back on tornado’s logger

  property mathjax_config: str
  property mathjax_url: str
  async prepare(*, _redirect_to_login=True)

    Prepare a response.

    Return type:

      `Awaitable`[`None`] | `None`

  render_template(name, **ns)

    Render a template by name.

  property serverapp: ServerApp | None
  property session_manager: SessionManager
  set_attachment_header(filename)

    Set Content-Disposition: attachment header

    As a method to ensure handling of filename encoding

    Return type:

      `None`

  set_cors_headers()

    Add CORS headers, if defined

    Now that current_user is async (jupyter-server 2.0), must be called at the end of prepare(), instead of in set_default_headers.

    Return type:

      `None`

  set_default_headers()

    Add CORS headers, if defined

    Return type:

      `None`

  property template_namespace: dict[str, Any]
  property terminal_manager: TerminalManager
  property version_hash: str

    The version hash to use for cache hints for static files

  write_error(status_code, **kwargs)

    render custom error pages

    Return type:

      `None`

  property ws_url: str

class jupyter_server.base.handlers.MainHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  Simple handler for base_url.

  get()

    Get the main template.

    Return type:

      `None`

  post()

    Get the main template.

    Return type:

      `None`

  put()

    Get the main template.

    Return type:

      `None`

class jupyter_server.base.handlers.PrometheusMetricsHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  Return prometheus metrics for this server

  get()

    Get prometheus metrics.

    Return type:

      `None`

class jupyter_server.base.handlers.PublicStaticFileHandler(application, request, **kwargs)

  Bases: `StaticFileHandler`

  Same as web.StaticFileHandler, but decorated to acknowledge that auth is not required.

  get(path, include_body=True)
    Return type:

      `Coroutine`[`Any`, `Any`, `None`]

  head(path)
    Return type:

      `Awaitable`[`None`]

class jupyter_server.base.handlers.RedirectWithParams(application, request, **kwargs)

  Bases: `RequestHandler`

  Same as web.RedirectHandler, but preserves URL parameters

  get()

    Get a redirect.

    Return type:

      `None`

  initialize(url, permanent=True)

    Initialize a redirect handler.

    Return type:

      `None`

class jupyter_server.base.handlers.Template404(application, request, **kwargs)

  Bases: `JupyterHandler`

  Render our 404 template

  async prepare()

    Prepare a 404 response.

    Return type:

      `None`

class jupyter_server.base.handlers.TrailingSlashHandler(application, request, **kwargs)

  Bases: `RequestHandler`

  Simple redirect handler that strips trailing slashes

  This should be the first, highest priority handler.

  get()

    Handle trailing slashes in a get.

    Return type:

      `None`

  post()

    Handle trailing slashes in a get.

    Return type:

      `None`

  put()

    Handle trailing slashes in a get.

    Return type:

      `None`

jupyter_server.base.handlers.json_errors(method)

  Decorate methods with this to return GitHub style JSON errors.

  This should be used on any JSON API on any handler method that can raise HTTPErrors.

  This will grab the latest HTTPError exception using sys.exc_info and then:

  1. Set the HTTP status code based on the HTTPError

  2. Create and return a JSON body with a message field describing the error in a human readable form.

  Return type:

    `Any`

jupyter_server.base.handlers.json_sys_info()

  Get sys info as json.

jupyter_server.base.handlers.log()

  Get the application log.

  Return type:

    `Logger`

Base websocket classes.

class jupyter_server.base.websocket.WebSocketMixin

  Bases: `object`

  Mixin for common websocket options

  check_origin(origin=None)

    Check Origin == Host or Access-Control-Allow-Origin.

    Tornado >= 4 calls this method automatically, raising 403 if it returns False.

  clear_cookie(*args, **kwargs)

    meaningless for websockets

  last_ping = 0.0
  last_pong = 0.0
  on_pong(data)

    Handle a pong message.

  open(*args, **kwargs)

    Open the websocket.

  ping_callback = None
  property ping_interval

    The interval for websocket keep-alive pings.

    Set ws_ping_interval = 0 to disable pings.

  property ping_timeout

    If no ping is received in this many milliseconds, close the websocket connection (VPNs, etc. can fail to cleanly close ws connections). Default is max of 3 pings or 30 seconds.

  prepare(*args, **kwargs)

    Handle a get request.

  send_ping()

    send a ping to keep the websocket alive

  stream: `Optional`[`IOStream`] = None

This module is deprecated in Jupyter Server 2.0

## Module contents