Python API#

jupyter_server_ydoc instantiates YDocExtension and stores it under serverapp.settings dictionary, under the "jupyter_server_ydoc" key. This instance can be used in other extensions to access the public API methods.

For example, to access a read-only view of the shared notebook model in your jupyter-server extension, you can use the get_document method:

collaboration = serverapp.settings["jupyter_server_ydoc"]
document = collaboration.get_document(
    path='Untitled.ipynb',
    content_type="notebook",
    file_format="json"
)
content = document.get()

API Reference#

class jupyter_server_ydoc.app.YDocExtension(**kwargs: Any)#
add_traits(**traits: Any) None#

Dynamically add trait attributes to the HasTraits instance.

answer_yes#

Answer yes to any prompts.

classmethod class_config_rst_doc() str#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str#

Get the config section for this class.

Parameters#

classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str#

Get the help string for this class in ReST format.

If inst is given, its current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str#

Get the helptext string for a single trait.

Parameters:
  • inst – If given, its current trait values will be used in place of the class default.

  • helptext – If not given, uses the help attribute of the current trait.

classmethod class_own_trait_events(name: str) dict[str, EventHandler]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None#

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata: Any) list[str]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

classmethod clear_instance() None#

unset _instance for this class and singleton parents.

cli_config#

The subset of our configuration that came from the command-line

We re-load this configuration after loading config files, to ensure that it maintains highest priority.

config_file#

Full path of a config file.

config_file_name#

Specify a config file to load.

property config_file_paths#

Look on the same path as our parent for config files

property cross_validation_lock: Any#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

current_activity()#

Return a list of activity happening in this extension.

disable_rtc#

Whether to disable real time collaboration.

document_cleanup_delay#

The delay in seconds to keep a document in memory in the back-end after all clients disconnect. Defaults to 60s, if None then the document will be kept in memory forever.

document_config_options() str#

Generate rST format documentation for the config options this application

Returns a multiline string.

document_save_delay#

The delay in seconds to wait after a change is made to a document before saving it. Defaults to 1s, if None then the document will never be saved.

emit_alias_help() Generator[str, None, None]#

Yield the lines for alias part of the help.

emit_description() Generator[str, None, None]#

Yield lines with the application description.

emit_examples() Generator[str, None, None]#

Yield lines with the usage and examples.

This usage string goes at the end of the command line help string and should contain examples of the application’s usage.

emit_flag_help() Generator[str, None, None]#

Yield the lines for the flag part of the help.

emit_help(classes: bool = False) Generator[str, None, None]#

Yield the help-lines for each Configurable class in self.classes.

If classes=False (the default), only flags and aliases are printed.

emit_help_epilogue(classes: bool) Generator[str, None, None]#

Yield the very bottom lines of the help message.

If classes=False (the default), print –help-all msg.

emit_options_help() Generator[str, None, None]#

Yield the lines for the options part of the help.

emit_subcommands_help() Generator[str, None, None]#

Yield the lines for the subcommand part of the help.

file_poll_interval#

The period in seconds to check for file changes on disk. Defaults to 1s, if 0 then file changes will only be checked when saving changes from the front-end.

flatten_flags() tuple[dict[str, Any], dict[str, Any]]#

Flatten flags and aliases for loaders, so cl-args override as expected.

This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect (key: longname) and not key: (longname, help) items.

Only aliases with exactly one descendent in the class list will be promoted.

generate_config#

Generate default config file.

generate_config_file(classes: List[Type[Configurable]] | None = None) str#

generate default config file from Configurables

get_default_logging_config() Dict[str, Any]#

Return the base logging configuration.

The default is to log to stderr using a StreamHandler, if no default handler already exists.

The log handler level starts at logging.WARN, but this can be adjusted by setting the log_level attribute.

The logging_config trait is merged into this allowing for finer control of logging.

async get_document(*, path: str | None = None, content_type: str | None = None, file_format: Literal['json', 'text'] | None = None, room_id: str | None = None, copy: bool = True) YBaseDoc | None#

Get a view of the shared model for the matching document.

You need to provide either a room_id or the path, the content_type and the file_format.

If copy=True, the returned shared model is a fork, meaning that any changes

made to it will not be propagated to the shared model used by the application.

classmethod get_extension_package()#

Get an extension package.

classmethod get_extension_point()#

Get an extension point.

handlers: List[tuple[t.Any, ...]]#

Handlers appended to the server.

has_trait(name: str) bool#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

initialize()#

Initialize the extension app. The corresponding server app and webapp should already be initialized by this step.

  • Appends Handlers to the ServerApp,

  • Passes config and settings from ExtensionApp to the Tornado web application

  • Points Tornado Webapp to templates and static assets.

initialize_handlers()#

Override this method to append handlers to a Jupyter Server.

classmethod initialize_server(argv=None, load_other_extensions=True, **kwargs)#

Creates an instance of ServerApp and explicitly sets this extension to enabled=True (i.e. superseding disabling found in other config from files).

The launch_instance method uses this method to initialize and start a server.

initialize_settings()#

Override this method to add handling of settings.

initialize_subcommand(subc: str, argv: List[str] | None = None) None#

Initialize a subcommand with argv.

initialize_templates()#

Override this method to add handling of template files.

classmethod initialized() bool#

Has an instance been created?

classmethod instance(*args: Any, **kwargs: Any) CT#

Returns a global instance of this class.

This method create a new instance if none have previously been created and returns a previously created instance is one already exists.

The arguments and keyword arguments passed to this method are passed on to the __init__() method of the class upon instantiation.

Examples#

Create a singleton class using instance, and retrieve it:

>>> from traitlets.config.configurable import SingletonConfigurable
>>> class Foo(SingletonConfigurable): pass
>>> foo = Foo.instance()
>>> foo == Foo.instance()
True

Create a subclass that is retrieved using the base class instance:

>>> class Bar(SingletonConfigurable): pass
>>> class Bam(Bar): pass
>>> bam = Bam.instance()
>>> bam == Bar.instance()
True
json_config_loader_class#

alias of JSONFileConfigLoader

classmethod launch_instance(argv=None, **kwargs)#

Launch the extension like an application. Initializes+configs a stock server and appends the extension to the server. Then starts the server and routes to extension’s landing page.

classmethod load_classic_server_extension(serverapp)#

Enables extension to be loaded as classic Notebook (jupyter/notebook) extension.

load_config_environ() None#

Load config files by environment.

load_config_file(suppress_errors: bool = True) None#

Load the config file.

By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail.

property loaded_config_files: list[str]#

Currently loaded configuration files

log#

Logger or LoggerAdapter instance

log_datefmt#

The date format used by logging formatters for %(asctime)s

log_format#

The Logging format template

log_level#

Set the log level by value or name.

logging_config#

Configure additional log handlers.

The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings.

This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers.

If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema

This dictionary is merged with the base logging configuration which defines the following:

  • A logging formatter intended for interactive use called console.

  • A logging handler that writes to stderr called console which uses the formatter console.

  • A logger with the name of this application set to DEBUG level.

This example adds a new handler that writes to a file:

c.Application.logging_config = {
    "handlers": {
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "filename": "<path/to/file>",
        }
    },
    "loggers": {
        "<application-name>": {
            "level": "DEBUG",
            # NOTE: if you don't list the default "console"
            # handler here then it will be disabled
            "handlers": ["console", "file"],
        },
    },
}
classmethod make_serverapp(**kwargs: Any) ServerApp#

Instantiate the ServerApp

Override to customize the ServerApp before it loads any configuration

migrate_config() None#

Migrate config/data from IPython 3

notify_change(change: Bunch) None#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

nameslist, str, All

If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

typestr, All (default: ‘change’)

The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters#

handlercallable, None

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

namelist, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

removebool

If False (the default), then install the handler. If True then unintall it.

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: List[str] | None = None) None#

Parse the command line arguments.

print_alias_help() None#

Print the alias parts of the help.

print_description() None#

Print the application description.

print_examples() None#

Print usage and examples (see emit_examples()).

print_flag_help() None#

Print the flag part of the help.

print_help(classes: bool = False) None#

Print the help for each Configurable class in self.classes.

If classes=False (the default), only flags and aliases are printed.

print_options() None#

Print the options part of the help.

print_subcommands() None#

Print the subcommand part of the help.

print_version() None#

Print the version string.

python_config_loader_class#

alias of PyFileConfigLoader

classmethod section_names() list[str]#

return section names as a list

server_side_execution#

Whether to execute notebooks in the server using the REST API, not using the kernel protocol over WebSocket. The frontend only interacts with the notebook through its shared model.

serverapp_class#

alias of ServerApp

set_trait(name: str, value: Any) None#

Forcibly sets trait attribute, including read-only attributes.

settings#

Settings that will passed to the server.

setup_instance(**kwargs: Any) None#

This is called before self.__init__ is called.

show_config#

Instead of starting the Application, dump configuration to stdout

show_config_json#

Instead of starting the Application, dump configuration to stdout (as JSON)

start()#

Start the underlying Jupyter server.

Server should be started after extension is initialized.

start_show_config() None#

start function used when show_config is True

static_paths#

paths to search for serving static files.

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

static_url_prefix#

Url where the static assets for the extension are served.

stop()#

Stop the underlying Jupyter server.

async stop_extension()#

Cleanup any resources managed by this extension.

template_paths#

Paths to search for serving jinja templates.

Can be used to override templates from notebook.templates.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel#

Return a trait’s default value or a dictionary of them

Notes#

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler]#

Get a dict of all the event handlers of this class.

Parameters#

namestr (default: None)

The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns#

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns#

A dict of trait names and their values.

Notes#

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

typestr or All (default: ‘change’)

The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

update_config(config: Config) None#

Update config and load the new values

write_default_config() None#

Write our default config to a .py config file

ystore_class#

The YStore class to use for storing Y updates. Defaults to an SQLiteYStore, which stores Y updates in a ‘.jupyter_ystore.db’ SQLite database in the current directory.

class jupyter_server_ydoc.handlers.DocForkHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)#

Jupyter Server handler to: - create a fork of a root document (optionally synchronizing with the root document), - delete a fork of a root document (optionally merging back in the root document). - get fork IDs of a root document.

add_header(name: str, value: bytes | str | int | Integral | datetime) None#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

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

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. For example:

self.set_etag_header()
if self.check_etag_header():
    self.set_status(304)
    return

This method is called automatically when the request is finished, but may be called earlier for applications that override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

check_host() bool#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool#

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

check_referer() bool#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

Clear a login cookie.

compute_etag() str | None#

Computes the etag header to be used for this request.

By default uses a hash of the content written so far.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically the first time self.current_user is accessed. get_current_user() will only be called once per request, and is cached for future access:

    def get_current_user(self):
        user_cookie = self.get_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str#

Decodes an argument from the request.

The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

delete(fork_roomid)#

Deletes a forked document, and optionally merges it back in the root document.

detach() IOStream#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(*args: Any, **kwargs: Any) Future[Any]#

Finish an API response.

flush(include_footers: bool = False) Future[None]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

get(root_roomid)#

Returns a dictionary of fork room ID to fork room information for the given root room ID.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() str#

Get the current user.

get_json_body() dict[str, Any] | None#

Return the body of the request as JSON data.

get_login_url() str#

Get the login url.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int#

Returns the status code for our response.

get_template(name)#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any]#

Returns a dictionary to be used as the default template namespace.

May be overridden by subclasses to add or modify values.

The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize(ywebsocket_server: JupyterWebsocketServer) None#
property jinja_template_vars: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

property log: Logger#

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

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

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.

on_connection_close() None#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

options(*args: Any, **kwargs: Any) None#

Get the options.

async prepare() None#

Prepare an API response.

put(root_roomid)#

Creates a fork of a root document and returns its ID. Optionally keeps the fork in sync with the root.

redirect(url: str, permanent: bool = False, status: int | None = None) None#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

render_template(name, **ns)#

Render a template by name.

require_setting(name: str, feature: str = 'this feature') None#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

set_attachment_header(filename: str) None#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_cors_headers() None#

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.

set_default_headers() None#

Add CORS headers, if defined

set_etag_header() None#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

skip_check_origin() bool#

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.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

update_api_activity() None#

Update last_activity of API requests

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None#

APIHandler errors are JSON, not human pages

xsrf_form_html() str#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class jupyter_server_ydoc.handlers.DocSessionHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)#

Jupyter Server’s handler to retrieve the document’s session.

add_header(name: str, value: bytes | str | int | Integral | datetime) None#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

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

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. For example:

self.set_etag_header()
if self.check_etag_header():
    self.set_status(304)
    return

This method is called automatically when the request is finished, but may be called earlier for applications that override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

check_host() bool#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool#

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

check_referer() bool#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

Clear a login cookie.

compute_etag() str | None#

Computes the etag header to be used for this request.

By default uses a hash of the content written so far.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically the first time self.current_user is accessed. get_current_user() will only be called once per request, and is cached for future access:

    def get_current_user(self):
        user_cookie = self.get_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str#

Decodes an argument from the request.

The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(*args: Any, **kwargs: Any) Future[Any]#

Finish an API response.

flush(include_footers: bool = False) Future[None]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() str#

Get the current user.

get_json_body() dict[str, Any] | None#

Return the body of the request as JSON data.

get_login_url() str#

Get the login url.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int#

Returns the status code for our response.

get_template(name)#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any]#

Returns a dictionary to be used as the default template namespace.

May be overridden by subclasses to add or modify values.

The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None#
property jinja_template_vars: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

property log: Logger#

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

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

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.

on_connection_close() None#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

options(*args: Any, **kwargs: Any) None#

Get the options.

async prepare() None#

Prepare an API response.

put(path)#

Creates a new session for a given document or returns an existing one.

redirect(url: str, permanent: bool = False, status: int | None = None) None#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

render_template(name, **ns)#

Render a template by name.

require_setting(name: str, feature: str = 'this feature') None#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

set_attachment_header(filename: str) None#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_cors_headers() None#

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.

set_default_headers() None#

Add CORS headers, if defined

set_etag_header() None#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

skip_check_origin() bool#

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.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

update_api_activity() None#

Update last_activity of API requests

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None#

APIHandler errors are JSON, not human pages

xsrf_form_html() str#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class jupyter_server_ydoc.handlers.TimelineHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)#
add_header(name: str, value: bytes | str | int | Integral | datetime) None#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

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

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. For example:

self.set_etag_header()
if self.check_etag_header():
    self.set_status(304)
    return

This method is called automatically when the request is finished, but may be called earlier for applications that override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

check_host() bool#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool#

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

check_referer() bool#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

Clear a login cookie.

compute_etag() str | None#

Computes the etag header to be used for this request.

By default uses a hash of the content written so far.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically the first time self.current_user is accessed. get_current_user() will only be called once per request, and is cached for future access:

    def get_current_user(self):
        user_cookie = self.get_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str#

Decodes an argument from the request.

The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(*args: Any, **kwargs: Any) Future[Any]#

Finish an API response.

flush(include_footers: bool = False) Future[None]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() str#

Get the current user.

get_json_body() dict[str, Any] | None#

Return the body of the request as JSON data.

get_login_url() str#

Get the login url.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int#

Returns the status code for our response.

get_template(name)#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any]#

Returns a dictionary to be used as the default template namespace.

May be overridden by subclasses to add or modify values.

The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize(ystore_class: type[BaseYStore], ywebsocket_server: JupyterWebsocketServer) None#
property jinja_template_vars: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

property log: Logger#

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

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

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.

on_connection_close() None#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

options(*args: Any, **kwargs: Any) None#

Get the options.

async prepare() None#

Prepare an API response.

redirect(url: str, permanent: bool = False, status: int | None = None) None#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

render_template(name, **ns)#

Render a template by name.

require_setting(name: str, feature: str = 'this feature') None#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

set_attachment_header(filename: str) None#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_cors_headers() None#

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.

set_default_headers() None#

Add CORS headers, if defined

set_etag_header() None#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

skip_check_origin() bool#

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.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

update_api_activity() None#

Update last_activity of API requests

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None#

APIHandler errors are JSON, not human pages

xsrf_form_html() str#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class jupyter_server_ydoc.handlers.UndoRedoHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)#
add_header(name: str, value: bytes | str | int | Integral | datetime) None#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

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

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. For example:

self.set_etag_header()
if self.check_etag_header():
    self.set_status(304)
    return

This method is called automatically when the request is finished, but may be called earlier for applications that override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

check_host() bool#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool#

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

check_referer() bool#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

Clear a login cookie.

compute_etag() str | None#

Computes the etag header to be used for this request.

By default uses a hash of the content written so far.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically the first time self.current_user is accessed. get_current_user() will only be called once per request, and is cached for future access:

    def get_current_user(self):
        user_cookie = self.get_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str#

Decodes an argument from the request.

The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(*args: Any, **kwargs: Any) Future[Any]#

Finish an API response.

flush(include_footers: bool = False) Future[None]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() str#

Get the current user.

get_json_body() dict[str, Any] | None#

Return the body of the request as JSON data.

get_login_url() str#

Get the login url.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int#

Returns the status code for our response.

get_template(name)#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any]#

Returns a dictionary to be used as the default template namespace.

May be overridden by subclasses to add or modify values.

The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize(ywebsocket_server: JupyterWebsocketServer) None#
property jinja_template_vars: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

property log: Logger#

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

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

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.

on_connection_close() None#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

options(*args: Any, **kwargs: Any) None#

Get the options.

async prepare() None#

Prepare an API response.

redirect(url: str, permanent: bool = False, status: int | None = None) None#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

render_template(name, **ns)#

Render a template by name.

require_setting(name: str, feature: str = 'this feature') None#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

set_attachment_header(filename: str) None#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_cors_headers() None#

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.

set_default_headers() None#

Add CORS headers, if defined

set_etag_header() None#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

skip_check_origin() bool#

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.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

update_api_activity() None#

Update last_activity of API requests

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None#

APIHandler errors are JSON, not human pages

xsrf_form_html() str#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class jupyter_server_ydoc.handlers.YDocWebSocketHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)#

YDocWebSocketHandler uses the singleton pattern for WebsocketServer, which is a subclass of ypy-websocket’s WebsocketServer.

In WebsocketServer, we expect to use a WebSocket object as follows:

  • receive messages until the connection is closed with

    for message in websocket: pass.

  • send a message with await websocket.send(message).

Tornado’s WebSocket API is different, so YDocWebSocketHandler needs to be adapted:

  • YDocWebSocketHandler is an async iterator, that will yield received messages.

    Messages received in Tornado’s on_message(message) are put in an async _message_queue, from which we get them asynchronously.

  • The send(message) method is async and calls Tornado’s write_message(message).

  • Although it’s currently not used in ypy-websocket, recv() is an async method for

    receiving a message.

add_header(name: str, value: bytes | str | int | Integral | datetime) None#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

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

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. For example:

self.set_etag_header()
if self.check_etag_header():
    self.set_status(304)
    return

This method is called automatically when the request is finished, but may be called earlier for applications that override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

check_host() bool#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin)#

Check origin

check_referer() bool#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

Clear a login cookie.

close(code: int | None = None, reason: str | None = None) None#

Closes this Web Socket.

Once the close handshake is successful the socket will be closed.

code may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1. reason may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.

Changed in version 4.0: Added the code and reason arguments.

compute_etag() str | None#

Computes the etag header to be used for this request.

By default uses a hash of the content written so far.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically the first time self.current_user is accessed. get_current_user() will only be called once per request, and is cached for future access:

    def get_current_user(self):
        user_cookie = self.get_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str#

Decodes an argument from the request.

The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

async get(*args, **kwargs)#

Overrides default behavior to check whether the client is authenticated or not.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

get_compression_options() Dict[str, Any] | None#

Override to return compression options for the connection.

If this method returns None (the default), compression will be disabled. If it returns a dict (even an empty one), it will be enabled. The contents of the dict may be used to control the following compression options:

compression_level specifies the compression level.

mem_level specifies the amount of memory used for the internal compression state.

These parameters are documented in details here: https://docs.python.org/3.6/library/zlib.html#zlib.compressobj

Added in version 4.1.

Changed in version 4.5: Added compression_level and mem_level.

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() str#

Get the current user.

get_json_body() dict[str, Any] | None#

Return the body of the request as JSON data.

get_login_url() str#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int#

Returns the status code for our response.

get_template(name)#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any]#

Returns a dictionary to be used as the default template namespace.

May be overridden by subclasses to add or modify values.

The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize(ywebsocket_server: JupyterWebsocketServer, file_loaders: FileLoaderMapping, ystore_class: type[BaseYStore], document_cleanup_delay: float | None = 60.0, document_save_delay: float | None = 1.0) None#
property jinja_template_vars: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

property log: Logger#

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

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

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.

property max_message_size#

Override max_message size to 1GB

on_close() None#

On connection close.

on_connection_close() None#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

async on_message(message)#

On message receive.

on_ping(data: bytes) None#

Invoked when the a ping frame is received.

on_pong(data: bytes) None#

Invoked when the response to a ping frame is received.

async open(room_id)#

On connection open.

property path#

Returns the room id. It needs to be called ‘path’ for compatibility with the WebsocketServer (websocket.path).

ping(data: str | bytes = b'') None#

Send ping frame to the remote end.

The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications.

Consider using the websocket_ping_interval application setting instead of sending pings manually.

Changed in version 5.1: The data argument is now optional.

property ping_interval: float | None#

The interval for websocket keep-alive pings.

Set websocket_ping_interval = 0 to disable pings.

property ping_timeout: float | None#

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

async prepare()#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

async recv()#

Receive a message from the client.

redirect(url: str, permanent: bool = False, status: int | None = None) None#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

render_template(name, **ns)#

Render a template by name.

require_setting(name: str, feature: str = 'this feature') None#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str#

Alias for Application.reverse_url.

select_subprotocol(subprotocols: List[str]) str | None#

Override to implement subprotocol negotiation.

subprotocols is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, or None to not select a subprotocol.

Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.

The list may be empty, in which case this method must return None. This method is always called exactly once even if no subprotocols were proposed so that the handler can be advised of this fact.

Changed in version 5.1: Previously, this method was called with a list containing an empty string instead of an empty list if no subprotocols were proposed by the client.

property selected_subprotocol: str | None#

The subprotocol returned by select_subprotocol.

Added in version 5.1.

async send(message)#

Send a message to the client.

send_error(status_code: int = 500, **kwargs: Any) None#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

set_attachment_header(filename: str) None#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_cors_headers() None#

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.

set_default_headers() None#

Add CORS headers, if defined

set_etag_header() None#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

set_nodelay(value: bool) None#

Set the no-delay flag for this stream.

By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call self.set_nodelay(True) once the websocket connection is established.

See .BaseIOStream.set_nodelay for additional details.

Added in version 3.1.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

skip_check_origin() bool#

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.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None#

render custom error pages

write_message(message: bytes | str | Dict[str, Any], binary: bool = False) Future[None]#

Sends the given message to the client of this Web Socket.

The message may be either a string or a dict (which will be encoded as json). If the binary argument is false, the message will be sent as utf8; in binary mode any byte string is allowed.

If the connection is already closed, raises WebSocketClosedError. Returns a .Future which can be used for flow control.

Changed in version 3.2: WebSocketClosedError was added (previously a closed connection would raise an AttributeError)

Changed in version 4.3: Returns a .Future which can be used for flow control.

Changed in version 5.0: Consistently raises WebSocketClosedError. Previously could sometimes raise .StreamClosedError.

xsrf_form_html() str#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.