jupyter_server package#



Manager to read and modify config data in JSON files.

class jupyter_server.config_manager.BaseJSONConfigManager(**kwargs: Any)#

Bases: LoggingConfigurable

General JSON config manager

Deals with persisting/storing config in a json file with optionally default values in a {section_name}.d directory.


A trait for unicode strings.


Returns the directory name for the section name: {config_dir}/{section_name}.d


Will try to create the config_dir directory.


Returns the json filename for the section_name: {config_dir}/{section_name}.json

get(section_name, include_root=True)#

Retrieve the config data for the specified section.

Returns the data as a dictionary, or an empty dictionary if the file doesn’t exist.

When include_root is False, it will not read the root .json file, effectively returning the default values.


A boolean (True, False) trait.

set(section_name, data)#

Store the given config data.

update(section_name, new_data)#

Modify the config section by recursively updating it with new_data.

Returns the modified config data as a dictionary.

jupyter_server.config_manager.recursive_update(target, new)#

Recursively update one dictionary using another.

None values will delete their keys.

jupyter_server.config_manager.remove_defaults(data, defaults)#

Recursively remove items from dict that are already in defaults

Log utilities.


log a bit more information about each request than tornado’s default

  • move static file get success to debug-level (reduces noise)

  • get proxied IP instead of proxy IP

  • log referer for redirect and failed requests

  • log user-agent for failed requests

A tornado based Jupyter server.

class jupyter_server.serverapp.JupyterPasswordApp(**kwargs: Any)#

Bases: JupyterApp

Set a password for the Jupyter server.

Setting a password secures the Jupyter server and removes the need for token-based authentication.

description: str = 'Set a password for the Jupyter server.\n\n    Setting a password secures the Jupyter server\n    and removes the need for token-based authentication.\n    '#

Start the password app.

class jupyter_server.serverapp.JupyterServerListApp(**kwargs: Any)#

Bases: JupyterApp

An application to list running Jupyter servers.

description: str = 'List currently running Jupyter servers.'#
flags: t.Dict[t.Union[str, t.Tuple[str, ...]], t.Tuple[t.Union[t.Dict[str, t.Any], Config], str]] = {'json': ({'JupyterServerListApp': {'json': True}}, 'Produce machine-readable JSON object on each line of output.'), 'jsonlist': ({'JupyterServerListApp': {'jsonlist': True}}, 'Produce machine-readable JSON list output.')}#

If True, each line of output will be a JSON object with the details from the server info file. For a JSON list output, see the JupyterServerListApp.jsonlist configuration value


If True, the output will be a JSON list of objects, one per active Jupyer server, each with the details from the relevant server info file.


Start the server list application.

version: str = '2.7.3'#
class jupyter_server.serverapp.JupyterServerStopApp(**kwargs: Any)#

Bases: JupyterApp

An application to stop a Jupyter server.

description: str = 'Stop currently running Jupyter server for a given port'#

Parse command line options.


Port of the server to be killed. Default 8888


Shut down a server.


UNIX socket of the server to be killed.


Start the server stop app.

version: str = '2.7.3'#
class jupyter_server.serverapp.ServerApp(**kwargs: Any)#

Bases: JupyterApp

The Jupyter Server application class.

aliases: t.Dict[t.Union[str, t.Tuple[str, ...]], t.Union[str, t.Tuple[str, str]]]#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.


true header


Set the Access-Control-Allow-Credentials


Whether or not to allow external kernels, whose connection files are placed in external_connection_dir.


Set the Access-Control-Allow-Origin header

Use ‘*’ to allow any origin to access your server.

Takes precedence over allow_origin_pat.


Use a regular expression for the Access-Control-Allow-Origin header

Requests from an origin matching the expression will get replies with:

Access-Control-Allow-Origin: origin

where origin is the origin of the request.

Ignored if allow_origin is set.


DEPRECATED in 2.0. Use PasswordIdentityProvider.allow_password_change


Allow requests where the Host header doesn’t point to a local server

By default, requests get a 403 forbidden response if the ‘Host’ header shows that the browser thinks it’s on a non-local domain. Setting this option to True disables this check.

This protects against ‘DNS rebinding’ attacks, where a remote web server serves you a page and then changes its DNS to send later requests to a local IP, bypassing same-origin checks.

Local IP addresses (such as and ::1) are allowed as local, along with hostnames configured in local_hostnames.


Whether to allow the user to run the server as root.


” Require authentication to access prometheus metrics.


The authorizer class to use.


Reload the webapp when changes are made to any Python src files.


The base URL for the Jupyter server.

Leading and trailing slashes can be omitted, and will automatically be added.


Specify what command to use to invoke a web browser when starting the server. If not specified, the default browser will be determined by the webbrowser standard library module, which allows setting of the BROWSER environment variable to override it.


A trait for unicode strings.


A trait for unicode strings.


The full path to an SSL/TLS certificate file.

classes: t.List[t.Type[t.Any]] = [<class 'jupyter_client.manager.KernelManager'>, <class 'jupyter_client.session.Session'>, <class 'jupyter_server.services.kernels.kernelmanager.MappingKernelManager'>, <class 'jupyter_client.kernelspec.KernelSpecManager'>, <class 'jupyter_server.services.kernels.kernelmanager.AsyncMappingKernelManager'>, <class 'jupyter_server.services.contents.manager.ContentsManager'>, <class 'jupyter_server.services.contents.filemanager.FileContentsManager'>, <class 'jupyter_server.services.contents.manager.AsyncContentsManager'>, <class 'jupyter_server.services.contents.filemanager.AsyncFileContentsManager'>, <class 'nbformat.sign.NotebookNotary'>, <class 'jupyter_server.gateway.managers.GatewayMappingKernelManager'>, <class 'jupyter_server.gateway.managers.GatewayKernelSpecManager'>, <class 'jupyter_server.gateway.managers.GatewaySessionManager'>, <class 'jupyter_server.gateway.connections.GatewayWebSocketConnection'>, <class 'jupyter_server.gateway.gateway_client.GatewayClient'>, <class 'jupyter_server.auth.authorizer.Authorizer'>, <class 'jupyter_events.logger.EventLogger'>, <class 'jupyter_server.services.kernels.connection.channels.ZMQChannelsWebsocketConnection'>]#
async cleanup_extensions()#

Call shutdown hooks in all extensions.

async cleanup_kernels()#

Shutdown all kernels.

The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files.


The full path to a certificate authority certificate for SSL/TLS client authentication.


The config manager class to use

property connection_url#

The content manager class to use.


DEPRECATED. Use IdentityProvider.cookie_options


The random bytes used to secure cookies. By default this is a new random number every time you start the server. Set it to a value in a config file to enable logins to persist across server sessions.

Note: Cookie secrets should be kept private, do not share config files with cookie_secret stored in plaintext (you can read the value from a file).


The file where the cookie secret is stored.


Override URL shown to users.

Replace actual URL, including protocol, address, port and base URL, with the given value when displaying URL to the users. Do not change the actual connection URL. If authentication token is enabled, the token is added to the custom URL automatically.

This option is intended to be used when the URL to display to the user cannot be determined reliably by the Jupyter server (proxified or containerized setups for example).

default_services = ('api', 'auth', 'config', 'contents', 'files', 'kernels', 'kernelspecs', 'nbconvert', 'security', 'sessions', 'shutdown', 'view', 'events')#

The default URL to redirect to from /

description: str = 'The Jupyter Server.\n\n    This launches a Tornado-based Jupyter Server.'#

Disable cross-site-request-forgery protection

Jupyter server includes protection from cross-site request forgeries, requiring API requests to either:

  • originate from pages served by this server (validated with XSRF cookie and token), or

  • authenticate with a token

Some anonymous compute resources still desire the ability to run code, completely without authentication. These services can disable all authentication and security checks, with the full knowledge of what that implies.

property display_url#

Human readable string with URLs for interacting with the running Jupyter Server


An EventLogger for emitting structured event data from Jupyter Server and extensions.

examples: t.Union[str, Unicode] = '\njupyter server                       # start the server\njupyter server  --certfile=mycert.pem # use SSL/TLS certificate\njupyter server password              # enter a password to protect the server\n'#

The directory to look at for external kernel connection files, if allow_external_kernels is True. Defaults to Jupyter runtime_dir/external_kernels. Make sure that this directory is not filled with left-over connection files, that could result in unnecessary kernel manager creations.


handlers that should be loaded at higher priority than the default services


Extra paths to search for serving static files.

This allows adding javascript/css to be available from the Jupyter server machine, or overriding individual files in the IPython


Extra paths to search for serving jinja templates.

Can be used to override templates from jupyter_server.templates.


Open the named file when the application is launched.


The URL prefix where files are opened directly.


Searches Jupyter paths for jpserver_extensions.

flags: t.Dict[t.Union[str, t.Tuple[str, ...]], t.Tuple[t.Union[t.Dict[str, t.Any], Config], str]]#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

DEPRECATED. Use IdentityProvider.get_secure_cookie_kwargs

property http_server#

An instance of Tornado’s HTTPServer class for the Server Web Application.


The identity provider class to use.


A trait for unicode strings.


Check the components submodule, and warn if it’s unclean


Initialize configurables.


Initialize the Event Bus.


Creates an instance of a Tornado HTTPServer for the Server Web Application and sets the http_server attribute.


init self.io_loop so that an extension can use it by io_loop.call_later() to create background tasks


Initialize logging.


initialize system resources


If an extension’s metadata includes an ‘app’ key, the value must be a subclass of ExtensionApp. An instance of the class will be created at this step. The config for this instance will inherit the ServerApp’s config object and load its own config.


Initialize a shutdown on no activity.


Initialize signal handlers.


initialize tornado webapp

initialize(argv=None, find_extensions=True, new_httpserver=True, starter_extension=None)#

Initialize the Server application class, configurables, web application, and http server.

  • argv (list or None) – CLI arguments to parse.

  • find_extensions (bool) – If True, find and load extensions listed in Jupyter config paths. If False, only load extensions that are passed to ServerApp directy through the argv, config, or jpserver_extensions arguments.

  • new_httpserver (bool) – If True, a tornado HTTPServer instance will be created and configured for the Server Web Application. This will set the http_server attribute of this class.

  • starter_extension (str) – If given, it references the name of an extension point that started the Server. We will try to load configuration from extension point


DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_data_rate_limit


DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_msg_rate_limit


The IP address the Jupyter server will listen on.


Supply extra arguments that will be passed to Jinja environment.


Extra variables to supply to jinja templates when rendering.


Dict of Python modules to load as Jupyter server extensions.Entry values can be used to enable and disable the loading ofthe extensions. The extensions will be loaded in alphabetical order.


The kernel manager class to use.


A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute


The kernel spec manager class to use. Should be a subclass of jupyter_client.kernelspec.KernelSpecManager.

The Api of KernelSpecManager is provisional and might change without warning between this version of Jupyter and the next stable one.


The kernel websocket connection class to use.


DEPRECATED. Use ZMQChannelsWebsocketConnection.kernel_ws_protocol


The full path to a private key file for usage with SSL/TLS.


Launch the browser.


DEPRECATED. Use ZMQChannelsWebsocketConnection.limit_rate


Load any extensions specified by config.

Import the module, then call the load_jupyter_server_extension function, if one exists.

The extension API is experimental, and may change in future releases.


Hostnames to allow as local when allow_remote_access is False.

Local IP addresses (such as and ::1) are automatically accepted as local as well.

property local_url#

The login handler class to use.


The logout handler class to use.


Sets the maximum allowed size of the client request body, specified in the Content-Length request header field. If the size in a request exceeds the configured value, a malformed HTTP message is returned to the client.

Note: max_body_size is applied even in streaming mode.


Gets or sets the maximum amount of memory, in bytes, that is allocated for use by the buffer manager.


Gets or sets a lower bound on the open file handles process resource limit. This may need to be increased if you run into an OSError: [Errno 24] Too many open files. This is not applicable when running on Windows.

name: t.Union[str, Unicode] = 'jupyter-server'#

If True, do not write redirect HTML file disk, or show in messages.


DEPRECATED, use root_dir.


Whether to open in a browser after starting. The specific browser used is platform dependent and determined by the python standard library webbrowser module, unless it is overridden using the –browser (ServerApp.browser) configuration option.


Parse the command line options.


DEPRECATED in 2.0. Use PasswordIdentityProvider.hashed_password


DEPRECATED in 2.0. Use PasswordIdentityProvider.password_required




The port the server will listen on (env

port_default_value = 8888#
port_env = 'JUPYTER_PORT'#



The number of additional ports to try if the specified port is not available (env

port_retries_default_value = 50#
port_retries_env = 'JUPYTER_PORT_RETRIES'#

Preferred starting directory to use for notebooks and kernels.

property public_url#

use %pylab or %matplotlib in the notebook to enable matplotlib.




If True, display controls to shut down the Jupyter server, such as menu items or buttons.


DEPRECATED. Use ZMQChannelsWebsocketConnection.rate_limit_window


Remove the jpserver-<pid>-open.html file created for this server.

Ignores the error raised when the file has already been removed.


Remove the browser_open_file and browser_open_file_to_run files created for this server.

Ignores the error raised when the file has already been removed.


Remove the jpserver-<pid>.json file created for this server.

Ignores the error raised when the file has already been removed.


Reraise exceptions encountered loading server extensions?


The directory to use for notebooks and kernels.


Return the current working directory and the server url information


Return a JSONable dict of information about this server.


The session manager class to use.


Shutdown server on timeout when there are no kernels or terminals.


it may shut down up to a minute later. 0 (the default) disables this automatic shutdown.


Shut down the server after N seconds with no kernelsrunning and no activity. This can be used together with culling idle kernels (MappingKernelManager.cull_idle_timeout) to shutdown the Jupyter server when it’s not in use. This is not precisely timed


The UNIX socket the Jupyter server will listen on.




The permissions mode for UNIX socket creation (default


Supply SSL options for the tornado HTTPServer. See the tornado docs for details.


Start the Jupyter server app, after initialization

This method takes no arguments so all configuration and initialization must be done prior to calling this method.


Start the Jupyter Server application.


Start the IO Loop.

property starter_app#

Get the Extension that started this server.


Path to search for custom.js, css

property static_file_path#

return extra paths + the default location


Paths to set up static files as immutable.

This allow setting up the cache control of static files as immutable. It should be used for static file named with a hash for instance.


Cleanup resources and stop the server.

subcommands: dict = {'extension': (<class 'jupyter_server.extension.serverextension.ServerExtensionApp'>, 'Work with Jupyter server extensions'), 'list': (<class 'jupyter_server.serverapp.JupyterServerListApp'>, 'List currently running Jupyter servers.'), 'password': (<class 'jupyter_server.serverapp.JupyterPasswordApp'>, 'Set a password for the Jupyter server.'), 'stop': (<class 'jupyter_server.serverapp.JupyterServerStopApp'>, 'Stop currently running Jupyter server for a given port')}#
property template_file_path#

return extra paths + the default locations


Supply overrides for terminado. Currently only supports “shell_command”.


Set to False to disable terminals.

This does not make the server more secure by itself. Anything the user can in a terminal, they can also do in a notebook.

Terminals may also be automatically disabled if the terminado package is not available.


DEPRECATED. Use IdentityProvider.token


Supply overrides for the tornado.web.Application that the Jupyter server uses.


Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headerssent by the upstream reverse proxy. Necessary if the proxy handles SSL


Disable launching browser by redirect file For versions of notebook > 5.7.2, a security feature measure was added that prevented the authentication token used to launch the browser from being visible. This feature makes it difficult for other users on a multi-user system from running code in your Jupyter session as you. However, some environments (like Windows Subsystem for Linux (WSL) and Chromebooks), launching a browser using a redirect file can lead the browser failing to load. This is because of the difference in file structures/paths between the runtime and the browser.

Disabling this setting to False will disable this behavior, allowing the browser to launch by using a URL and visible token (as before).

version: str = '2.7.3'#

Specify where to open the server on startup. This is the new argument passed to the standard library method webbrowser.open. The behaviour is not guaranteed, but depends on browser support. Valid values are:

  • 2 opens a new tab,

  • 1 opens a new window,

  • 0 opens in an existing window.

See the webbrowser.open documentation for details.


Set the tornado compression options for websocket connections.

This value will be returned from WebSocketHandler.get_compression_options(). None (default) will disable compression. A dict (even an empty one) will enable compression.

See the tornado docs for WebSocketHandler.get_compression_options for details.


The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn’t).

Should be in the form of an HTTP origin: ws[s]://hostname[:port]


Write an jpserver-<pid>-open.html file

This can be used to open the notebook in a browser


Write an browser_open_file and browser_open_file_to_run files

This can be used to open a file directly in a browser.


Write the result of server_info() to the JSON file info_file.

class jupyter_server.serverapp.ServerWebApplication(jupyter_app, default_services, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, event_logger, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options, *, authorizer=None, identity_provider=None, kernel_websocket_connection_class=None)#

Bases: Application

A server web application.

init_handlers(default_services, settings)#

Load the (URL pattern, handler) tuples for each component.

init_settings(jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, event_logger, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options=None, *, authorizer=None, identity_provider=None, kernel_websocket_connection_class=None)#

Initialize settings for the web application.


Get a UTC timestamp for when the server last did something.

Includes: API activity, kernel activity, kernel shutdown, and terminal activity.

jupyter_server.serverapp.list_running_servers(runtime_dir=None, log=None)#

Iterate over the server info files of running Jupyter servers.

Given a runtime directory, find jpserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running Jupyter server instance.


Load the (URL pattern, handler) tuples for each component.

jupyter_server.serverapp.random_ports(port, n)#

Generate a list of n random ports near the given port.

The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n].

jupyter_server.serverapp.shutdown_server(server_info, timeout=5, log=None)#

Shutdown a Jupyter server in a separate process.

server_info should be a dictionary as produced by list_running_servers().

Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after timeout seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL.

Returns True if the server was stopped by any means, False if stopping it failed (on Windows).

Custom trait types.

class jupyter_server.traittypes.InstanceFromClasses(klasses=None, args=None, kw=None, **kwargs)#

Bases: ClassBasedTraitType

A trait whose value must be an instance of a class in a specified list of classes. The value can also be an instance of a subclass of the specified classes. Subclasses can declare default classes by overriding the klass attribute


Get the default value repr.


Convert from a string.


Get the trait info.


Check that a given class is a subclasses found in the klasses list.


Initialize the trait.


Make the dynamic default for the trait.

validate(obj, value)#

Validate an instance.

class jupyter_server.traittypes.TypeFromClasses(default_value=traitlets.Undefined, klasses=None, **kwargs)#

Bases: ClassBasedTraitType

A trait whose value must be a subclass of a class in a specified list of classes.


The default value repr.


Returns a description of the trait.


Initialize an instance.


Check that a given class is a subclasses found in the klasses list.

validate(obj, value)#

Validates that the value is a valid object instance.

Translation related utilities. When imported, injects _ to builtins

Notebook related utilities

async jupyter_server.utils.async_fetch(urlstring, method='GET', body=None, headers=None, io_loop=None)#

Send an asynchronous HTTP, HTTPS, or HTTP+UNIX request to a Tornado Web Server. Returns a tornado HTTPResponse.


Copy of IPython.utils.process.check_pid

jupyter_server.utils.check_version(v, check)#

check version string v >= check

If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date.


Expand $VARS and ~names in a string, like a shell


In [2]: os.environ[‘FOO’]=’test’ In [3]: expand_path(‘variable FOO is $FOO’) Out[3]: ‘variable FOO is test’

jupyter_server.utils.fetch(urlstring, method='GET', body=None, headers=None)#

Send a HTTP, HTTPS, or HTTP+UNIX request to a Tornado Web Server. Returns a tornado HTTPResponse.

jupyter_server.utils.filefind(filename, path_dirs=None)#

Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through expandvars() and expanduser(). Thus a simple call:


will find the file in the current working dir, but:


Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user’s home directory.

  • filename (str) – The filename to look for.

  • path_dirs (str, None or sequence of str) – The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with filename, calling expandvars() and expanduser() before testing for existence.

Return type:

Raises IOError or returns absolute path to file.


Import and return bar given the string foo.bar. Calling bar = import_item("foo.bar") is the functional equivalent of executing the code from foo import bar. :type name: :param name: The fully qualified name of the module/package being imported. :type name: str


mod – The module that was imported.

Return type:

module object


Is the provided namespace a Python Namespace Package (PEP420).


Returns None if module is not importable.


Convert a local file path to a URL

async jupyter_server.utils.run_sync_in_loop(maybe_async)#

DEPRECATED: Use ensure_async from jupyter_core instead.

jupyter_server.utils.samefile_simple(path, other_path)#

Fill in for os.path.samefile when it is unavailable (Windows+py2).

Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn’t support the stat fields needed for identifying if it’s the same file (st_ino, st_dev).

Only to be used if os.path.samefile is not available.

  • path (str) – representing a path to a file

  • other_path (str) – representing a path to another file



Return type:

Boolean that is True if both path and other path are the same

jupyter_server.utils.to_api_path(os_path, root='')#

Convert a filesystem path to an API path

If given, root will be removed from the path. root must be a filesystem path already.

Return type:

NewType()(ApiPath, str)

jupyter_server.utils.to_os_path(path, root='')#

Convert an API path to a filesystem path

If given, root will be prepended to the path. root must be a filesystem path already.

Return type:



Checks whether a UNIX socket path on disk is in use by attempting to connect to it.


Convert a URL to a local file path


Escape special characters in a URL path

Turns ‘/foo bar/’ into ‘/foo%20bar/’


Determine whether a given URL is absolute


Join components of url into a relative url

Use to prevent double slash when joining subpath. This will leave the initial and final / in place


Unescape special characters in a URL path

Turns ‘/foo%20bar/’ into ‘/foo bar/’


Decodes a UNIX sock path string from an encoded sock path for the http+unix URI form.


Encodes a UNIX socket URL from a socket path for the http+unix URI form.


Encodes a UNIX socket path string from a socket path for the http+unix URI form.

Module contents#

The Jupyter Server