jupyter_server package#

Subpackages#

Submodules#

Manager to read and modify config data in JSON files.

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

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.

config_dir#

A trait for unicode strings.

directory(section_name)#

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

Return type:

str

ensure_config_dir_exists()#

Will try to create the config_dir directory.

Return type:

None

file_name(section_name)#

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

Return type:

str

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.

Return type:

dict[str, Any]

read_directory#

A boolean (True, False) trait.

set(section_name, data)#

Store the given config data.

Return type:

None

update(section_name, new_data)#

Modify the config section by recursively updating it with new_data.

Returns the modified config data as a dictionary.

Return type:

dict[str, Any]

jupyter_server.config_manager.recursive_update(target, new)#

Recursively update one dictionary using another.

None values will delete their keys.

Return type:

None

jupyter_server.config_manager.remove_defaults(data, defaults)#

Recursively remove items from dict that are already in defaults

Return type:

None

Log utilities.

jupyter_server.log.log_request(handler)#

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)#

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()#

Start the password app.

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

Bases: JupyterApp

An application to list running Jupyter servers.

description: str = 'List currently running Jupyter servers.'#
flags: StrDict = {'json': ({'JupyterServerListApp': {'json': True}}, 'Produce machine-readable JSON object on each line of output.'), 'jsonlist': ({'JupyterServerListApp': {'jsonlist': True}}, 'Produce machine-readable JSON list output.')}#
json#

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

jsonlist#

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()#

Start the server list application.

version: str = '2.13.0.dev0'#
class jupyter_server.serverapp.JupyterServerStopApp(**kwargs)#

Bases: JupyterApp

An application to stop a Jupyter server.

description: str = 'Stop currently running Jupyter server for a given port'#
parse_command_line(argv=None)#

Parse command line options.

port#

Port of the server to be killed. Default 8888

shutdown_server(server)#

Shut down a server.

sock#

UNIX socket of the server to be killed.

start()#

Start the server stop app.

version: str = '2.13.0.dev0'#
class jupyter_server.serverapp.ServerApp(**kwargs)#

Bases: JupyterApp

The Jupyter Server application class.

aliases: StrDict#

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.

allow_credentials#

true header

Type:

Set the Access-Control-Allow-Credentials

allow_external_kernels#

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

allow_origin#

Set the Access-Control-Allow-Origin header

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

Takes precedence over allow_origin_pat.

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.

allow_password_change#

DEPRECATED in 2.0. Use PasswordIdentityProvider.allow_password_change

allow_remote_access#

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 127.0.0.1 and ::1) are allowed as local, along with hostnames configured in local_hostnames.

allow_root#

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

authenticate_prometheus#

” Require authentication to access prometheus metrics.

authorizer_class#

The authorizer class to use.

autoreload#

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

base_url#

The base URL for the Jupyter server.

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

browser#

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.

browser_open_file#

A trait for unicode strings.

browser_open_file_to_run#

A trait for unicode strings.

certfile#

The full path to an SSL/TLS certificate file.

classes: ClassesType = [<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.

Return type:

None

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.

Return type:

None

client_ca#

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

config_manager_class#

The config manager class to use

property connection_url: str#
contents_manager_class#

The content manager class to use.

cookie_options#

DEPRECATED. Use IdentityProvider.cookie_options

cookie_secret#

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).

cookie_secret_file#

The file where the cookie secret is stored.

custom_display_url#

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')#
default_url#

The default URL to redirect to from /

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

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: str#

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

event_logger#

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

examples: str | Unicode[str, str | bytes] = '\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'#
external_connection_dir#

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.

extra_services#

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

extra_static_paths#

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_template_paths#

Extra paths to search for serving jinja templates.

Can be used to override templates from jupyter_server.templates.

file_to_run#

Open the named file when the application is launched.

file_url_prefix#

The URL prefix where files are opened directly.

find_server_extensions()#

Searches Jupyter paths for jpserver_extensions.

Return type:

None

flags: StrDict#

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: HTTPServer#

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

identity_provider_class#

The identity provider class to use.

info_file#

A trait for unicode strings.

init_components()#

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

Return type:

None

init_configurables()#

Initialize configurables.

Return type:

None

init_event_logger()#

Initialize the Event Bus.

Return type:

None

init_httpserver()#

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

Return type:

None

init_ioloop()#

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

Return type:

None

init_logging()#

Initialize logging.

Return type:

None

init_mime_overrides()#
Return type:

None

init_resources()#

initialize system resources

Return type:

None

init_server_extensions()#

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.

Return type:

None

init_shutdown_no_activity()#

Initialize a shutdown on no activity.

Return type:

None

init_signal()#

Initialize signal handlers.

Return type:

None

init_webapp()#

initialize tornado webapp

Return type:

None

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

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

Parameters:
  • 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 directly 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

Return type:

None

iopub_data_rate_limit#

DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_data_rate_limit

iopub_msg_rate_limit#

DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_msg_rate_limit

ip#

The IP address the Jupyter server will listen on.

jinja_environment_options#

Supply extra arguments that will be passed to Jinja environment.

jinja_template_vars#

Extra variables to supply to jinja templates when rendering.

jpserver_extensions#

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.

kernel_manager_class#

The kernel manager class to use.

kernel_spec_manager#

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

kernel_spec_manager_class#

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.

kernel_websocket_connection_class#

The kernel websocket connection class to use.

kernel_ws_protocol#

DEPRECATED. Use ZMQChannelsWebsocketConnection.kernel_ws_protocol

keyfile#

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

launch_browser()#

Launch the browser.

Return type:

None

limit_rate#

DEPRECATED. Use ZMQChannelsWebsocketConnection.limit_rate

load_server_extensions()#

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.

Return type:

None

local_hostnames#

Hostnames to allow as local when allow_remote_access is False.

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

property local_url: str#
login_handler_class#

The login handler class to use.

logout_handler_class#

The logout handler class to use.

max_body_size#

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.

max_buffer_size#

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

min_open_files_limit#

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: str | Unicode[str, str | bytes] = 'jupyter-server'#
no_browser_open_file#

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

notebook_dir#

DEPRECATED, use root_dir.

open_browser#

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_command_line(argv=None)#

Parse the command line options.

Return type:

None

password#

DEPRECATED in 2.0. Use PasswordIdentityProvider.hashed_password

password_required#

DEPRECATED in 2.0. Use PasswordIdentityProvider.password_required

port#

JUPYTER_PORT).

Type:

The port the server will listen on (env

port_default_value = 8888#
port_env = 'JUPYTER_PORT'#
port_retries#

JUPYTER_PORT_RETRIES).

Type:

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_dir#

Preferred starting directory to use for notebooks and kernels. ServerApp.preferred_dir is deprecated in jupyter-server 2.0. Use FileContentsManager.preferred_dir instead

property public_url: str#
pylab#

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

Type:

DISABLED

quit_button#

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

rate_limit_window#

DEPRECATED. Use ZMQChannelsWebsocketConnection.rate_limit_window

remove_browser_open_file()#

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

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

Return type:

None

remove_browser_open_files()#

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.

Return type:

None

remove_server_info_file()#

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

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

Return type:

None

reraise_server_extension_failures#

Reraise exceptions encountered loading server extensions?

root_dir#

The directory to use for notebooks and kernels.

running_server_info(kernel_count=True)#

Return the current working directory and the server url information

Return type:

str

server_info()#

Return a JSONable dict of information about this server.

Return type:

dict[str, Any]

session_manager_class#

The session manager class to use.

shutdown_no_activity()#

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

Return type:

None

shutdown_no_activity_timeout#

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

Type:

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

sock#

The UNIX socket the Jupyter server will listen on.

sock_mode#

0600).

Type:

The permissions mode for UNIX socket creation (default

ssl_options#

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

start()#

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.

Return type:

None

start_app()#

Start the Jupyter Server application.

Return type:

None

start_ioloop()#

Start the IO Loop.

Return type:

None

property starter_app: Any#

Get the Extension that started this server.

static_custom_path#

Path to search for custom.js, css

property static_file_path: list[str]#

return extra paths + the default location

static_immutable_cache#

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.

stop(from_signal=False)#

Cleanup resources and stop the server.

Return type:

None

subcommands: dict[str, t.Any] = {'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: list[str]#

return extra paths + the default locations

terminado_settings#

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

terminals_enabled#

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.

token#

DEPRECATED. Use IdentityProvider.token

tornado_settings#

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

trust_xheaders#

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

use_redirect_file#

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.13.0.dev0'#
webbrowser_open_new#

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.

websocket_compression_options#

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.

websocket_ping_interval#

Configure the websocket ping interval in seconds.

Websockets are long-lived connections that are used by some Jupyter Server extensions.

Periodic pings help to detect disconnected clients and keep the connection active. If this is set to None, then no pings will be performed.

When a ping is sent, the client has websocket_ping_timeout seconds to respond. If no response is received within this period, the connection will be closed from the server side.

websocket_ping_timeout#

Configure the websocket ping timeout in seconds.

See websocket_ping_interval for details.

websocket_url#

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_browser_open_file()#

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

This can be used to open the notebook in a browser

Return type:

None

write_browser_open_files()#

Write an browser_open_file and browser_open_file_to_run files

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

Return type:

None

write_server_info_file()#

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

Return type:

None

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, websocket_ping_interval=None, websocket_ping_timeout=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, websocket_ping_interval=None, websocket_ping_timeout=None)#

Initialize settings for the web application.

last_activity()#

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.

Return type:

Generator[Any, None, None]

jupyter_server.serverapp.load_handlers(name)#

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

Return type:

Any

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].

Return type:

Generator[int, None, None]

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

default_value_repr()#

Get the default value repr.

from_string(s)#

Convert from a string.

info()#

Get the trait info.

instance_from_importable_klasses(value)#

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

instance_init(obj)#

Initialize the trait.

make_dynamic_default()#

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.

default_value_repr()#

The default value repr.

info()#

Returns a description of the trait.

instance_init(obj)#

Initialize an instance.

subclass_from_klasses(value)#

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.

Return type:

HTTPResponse

jupyter_server.utils.check_pid(pid)#

Copy of IPython.utils.process.check_pid

Return type:

bool

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.

Return type:

bool

jupyter_server.utils.expand_path(s)#

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

Examples:

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

Return type:

str

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.

Return type:

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 occurrence 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:

filefind("myfile.txt")

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

filefind("~/myfile.txt")

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.

Parameters:
  • 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.

jupyter_server.utils.import_item(name)#

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: str :param name: The fully qualified name of the module/package being imported. :type name: str

Returns:

mod – The module that was imported.

Return type:

module object

jupyter_server.utils.is_namespace_package(namespace)#

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

https://www.python.org/dev/peps/pep-0420/#specification

Returns None if module is not importable.

Return type:

bool | None

jupyter_server.utils.path2url(path)#

Convert a local file path to a URL

Return type:

str

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.

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

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

Returns:

same

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:

str

jupyter_server.utils.unix_socket_in_use(socket_path)#

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

Return type:

bool

jupyter_server.utils.url2path(url)#

Convert a URL to a local file path

Return type:

str

jupyter_server.utils.url_escape(path)#

Escape special characters in a URL path

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

Return type:

str

jupyter_server.utils.url_is_absolute(url)#

Determine whether a given URL is absolute

Return type:

bool

jupyter_server.utils.url_path_join(*pieces)#

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

Return type:

str

jupyter_server.utils.url_unescape(path)#

Unescape special characters in a URL path

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

Return type:

str

jupyter_server.utils.urldecode_unix_socket_path(socket_path)#

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

Return type:

str

jupyter_server.utils.urlencode_unix_socket(socket_path)#

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

Return type:

str

jupyter_server.utils.urlencode_unix_socket_path(socket_path)#

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

Return type:

str

Module contents#

The Jupyter Server

class jupyter_server.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