On this page

panel.io Package#


io Package#

The io module contains utilities for loading JS components, embedding model state, and rendering panel objects.

class panel.io.PeriodicCallback(**params)[source]#

Bases: Parameterized

Periodic encapsulates a periodic callback which will run both in tornado based notebook environments and on bokeh server. By default the callback will run until the stop method is called, but count and timeout values can be set to limit the number of executions or the maximum length of time for which the callback will run. The callback may also be started and stopped by setting the running parameter to True or False respectively.

callback = param.Callable(allow_None=True, label=’Callback’)

The callback to execute periodically.

count = param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Count’)

Number of times the callback will be executed, by default this is unlimited.

log = param.Boolean(bounds=(0, 1), default=True, label=’Log’)

Whether the periodic callback should log its actions.

period = param.Integer(default=500, inclusive_bounds=(True, True), label=’Period’)

Period in milliseconds at which the callback is executed.

timeout = param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Timeout’)

Timeout in milliseconds from the start time at which the callback expires.

running = param.Boolean(bounds=(0, 1), default=False, label=’Running’)

Toggles whether the periodic callback is currently running.

property counter#

Returns the execution count of the periodic callback.

start()[source]#

Starts running the periodic callback.

stop()[source]#

Stops running the periodic callback.

class panel.io.Resources(*args, absolute=False, **kwargs)[source]#

Bases: Resources

adjust_paths(resources)[source]#

Computes relative and absolute paths for resources.

extra_resources(resources, resource_type)[source]#

Adds resources for ReactiveHTML components.

panel.io.ipywidget(obj: Any, **kwargs: Any)#

Returns an ipywidget model which renders the Panel object.

Requires jupyter_bokeh to be installed.

Parameters
  • obj (object) – Any Panel object or object which can be rendered with Panel

  • **kwargs (dict) – Keyword arguments passed to the pn.panel utility function

Return type

Returns an ipywidget model which renders the Panel object.

panel.io.push(doc: Document, comm: Comm, binary: bool = True) None[source]#

Pushes events stored on the document across the provided comm.

panel.io.push_notebook(*objs: Viewable) None[source]#

A utility for pushing updates to the frontend given a Panel object. This is required when modifying any Bokeh object directly in a notebook session.

Parameters

objs (panel.viewable.Viewable) –

panel.io.serve(panels: 'TViewableOrFunc' | Mapping[str, 'TViewableOrFunc'], port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str | list[str]] = None, loop: Optional[IOLoop] = None, show: bool = True, start: bool = True, title: Optional[str] = None, verbose: bool = True, location: bool = True, threaded: bool = False, admin: bool = False, **kwargs) threading.Thread | Server[source]#

Allows serving one or more panel objects on a single server. The panels argument should be either a Panel object or a function returning a Panel object or a dictionary of these two. If a dictionary is supplied the keys represent the slugs at which each app is served, e.g. serve({‘app’: panel1, ‘app2’: panel2}) will serve apps at /app and /app2 on the server.

Reference: https://panel.holoviz.org/user_guide/Deploy_and_Export.html#serving-multiple-apps

Parameters
  • panel (Viewable, function or {str: Viewable or function}) – A Panel object, a function returning a Panel object or a dictionary mapping from the URL slug to either.

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) –

    A list of hosts that can connect to the websocket.

    This is typically required when embedding a server app in an external web site.

    If None, “localhost” is used.

  • loop (tornado.ioloop.IOLoop (optional, default=IOLoop.current())) – The tornado IOLoop to run the Server on

  • show (boolean (optional, default=True)) – Whether to open the server in a new browser tab on start

  • start (boolean(optional, default=True)) – Whether to start the Server

  • title (str or {str: str} (optional, default=None)) – An HTML title for the application or a dictionary mapping from the URL slug to a customized title

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • threaded (boolean (default=False)) – Whether to start the server on a new Thread

  • admin (boolean (default=False)) – Whether to enable the admin panel

  • kwargs (dict) – Additional keyword arguments to pass to Server instance

panel.io.unlocked() Iterator[source]#

Context manager which unlocks a Document and dispatches ModelChangedEvents triggered in the context body to all sockets on current sessions.

panel.io.with_lock(func: Callable) Callable[source]#

Wrap a callback function to execute with a lock allowing the function to modify bokeh models directly.

Parameters

func (callable) – The callable to wrap

Returns

wrapper – Function wrapped to execute without a Document lock.

Return type

callable


admin Module#

Inheritance diagram of panel.io.admin
class panel.io.admin.Data(*, fig, holomap, widgets, fps, max_frames, size, dpi, filename, info, css, widget_location)[source]#

Bases: Parameterized

data = param.List(bounds=(0, None), default=[], label=’Data’)

class panel.io.admin.LogDataHandler(data)[source]#

Bases: StreamHandler

acquire()#

Acquire the I/O thread lock.

addFilter(filter)#

Add the specified filter to this handler.

close()#

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

createLock()#

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[source]#

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

filter(record)#

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

Changed in version 3.2: Allow filters to be just callables.

flush()#

Flushes the stream.

format(record)#

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

handle(record)#

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)#

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

release()#

Release the I/O thread lock.

removeFilter(filter)#

Remove the specified filter from this handler.

setFormatter(fmt)#

Set the formatter for this handler.

setLevel(level)#

Set the logging level of this handler. level must be an int or a str.

setStream(stream)#

Sets the StreamHandler’s stream to the specified value, if it is different.

Returns the old stream, if the stream was changed, or None if it wasn’t.

class panel.io.admin.LogFilter(name='')[source]#

Bases: Filter

filter(record)[source]#

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.


cache Module#

Implements memoization for functions with arbitrary arguments

panel.io.cache.cache(func=None, hash_funcs=None, max_items=None, policy='LRU', ttl=None, to_disk=False, cache_path='./cache')[source]#

Decorator to memoize functions with options to configure the caching behavior

Parameters
  • func (callable) – The function to cache.

  • hash_funcs (dict or None) – A dictionary mapping from a type to a function which returns a hash for an object of that type. If provided this will override the default hashing function provided by Panel.

  • policy (str) –

    A caching policy when max_items is set, must be one of:
    • FIFO: First in - First out

    • LRU: Least recently used

    • LFU: Least frequently used

  • ttl (float or None) – The number of seconds to keep an item in the cache, or None if the cache should not expire. The default is None.

  • to_disk (bool) – Whether to cache to disk using diskcache.

  • cache_dir (str) – Directory to cache to on disk.

panel.io.cache.compute_hash(func, hash_funcs, args, kwargs)[source]#

Computes a hash given a function and its arguments.

Parameters
  • func (callable) – The function to cache.

  • hash_funcs (dict) – A dictionary of custom hash functions indexed by type

  • args (tuple) – Arguments to hash

  • kwargs (dict) – Keyword arguments to hash


callbacks Module#

Inheritance diagram of panel.io.callbacks

Defines callbacks to be executed on a thread or by scheduling it on a running bokeh server.

class panel.io.callbacks.PeriodicCallback(**params)[source]#

Bases: Parameterized

Periodic encapsulates a periodic callback which will run both in tornado based notebook environments and on bokeh server. By default the callback will run until the stop method is called, but count and timeout values can be set to limit the number of executions or the maximum length of time for which the callback will run. The callback may also be started and stopped by setting the running parameter to True or False respectively.

callback = param.Callable(allow_None=True, label=’Callback’)

The callback to execute periodically.

count = param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Count’)

Number of times the callback will be executed, by default this is unlimited.

log = param.Boolean(bounds=(0, 1), default=True, label=’Log’)

Whether the periodic callback should log its actions.

period = param.Integer(default=500, inclusive_bounds=(True, True), label=’Period’)

Period in milliseconds at which the callback is executed.

timeout = param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Timeout’)

Timeout in milliseconds from the start time at which the callback expires.

running = param.Boolean(bounds=(0, 1), default=False, label=’Running’)

Toggles whether the periodic callback is currently running.

property counter#

Returns the execution count of the periodic callback.

start()[source]#

Starts running the periodic callback.

stop()[source]#

Stops running the periodic callback.


convert Module#

Inheritance diagram of panel.io.convert
class panel.io.convert.MockSessionContext(*args, document=None, **kwargs)[source]#

Bases: SessionContext

property destroyed: bool#

If True, the session has been discarded and cannot be used.

A new session with the same ID could be created later but this instance will not come back to life.

property id: ID#

The unique ID for the session associated with this context.

property server_context: ServerContext#

The server context for this session context

with_locked_document(*args)[source]#

Runs a function with the document lock held, passing the document to the function.

Subclasses must implement this method.

Parameters

func (callable) – function that takes a single parameter (the Document) and returns None or a Future

Returns

a Future containing the result of the function

class panel.io.convert.Request(headers: 'dict', cookies: 'dict', arguments: 'dict')[source]#

Bases: object

panel.io.convert.convert_apps(apps: List[str], dest_path: str | None = None, title: str | None = None, runtime: Runtimes = 'pyodide-worker', requirements: List[str] | Literal['auto'] | os.PathLike = 'auto', prerender: bool = True, build_index: bool = True, build_pwa: bool = True, pwa_config: Dict[Any, Any] = {}, max_workers: int = 4, panel_version: Literal['auto', 'local'] | str = 'auto', http_patch: bool = True, verbose: bool = True)[source]#
apps: str | List[str]

The filename(s) of the Panel/Bokeh application(s) to convert.

dest_path: str | pathlib.Path

The directory to write the converted application(s) to.

title: str | None

A title for the application(s). Also used to generate unique name for the application cache to ensure.

runtime: ‘pyodide’ | ‘pyscript’ | ‘pyodide-worker’

The runtime to use for running Python in the browser.

requirements: ‘auto’ | List[str] | os.PathLike

The list of requirements to include (in addition to Panel). By default automatically infers dependencies from imports in the application. May also provide path to a requirements.txt

prerender: bool

Whether to pre-render the components so the page loads.

build_index: bool

Whether to write an index page (if there are multiple apps).

build_pwa: bool

Whether to write files to define a progressive web app (PWA) including a manifest and a service worker that caches the application locally

pwa_config: Dict[Any, Any]

Configuration for the PWA including (see https://developer.mozilla.org/en-US/docs/Web/Manifest)

  • display: Display options (‘fullscreen’, ‘standalone’, ‘minimal-ui’ ‘browser’)

  • orientation: Preferred orientation

  • background_color: The background color of the splash screen

  • theme_color: The theme color of the application

max_workers: int

The maximum number of parallel workers

panel_version: ‘auto’ | ‘local’] | str

‘ The panel version to include.
http_patch: bool

Whether to patch the HTTP request stack with the pyodide-http library to allow urllib3 and requests to work.

panel.io.convert.script_to_html(filename: str, requirements: Literal['auto'] | List[str] = 'auto', js_resources: Literal['auto'] | List[str] = 'auto', css_resources: Literal['auto'] | List[str] | None = None, runtime: Runtimes = 'pyodide', prerender: bool = True, panel_version: Literal['auto', 'local'] | str = 'auto', manifest: str | None = None, http_patch: bool = True) str[source]#

Converts a Panel or Bokeh script to a standalone WASM Python application.

Parameters
  • filename (str) – The filename of the Panel/Bokeh application to convert.

  • requirements ('auto' | List[str]) – The list of requirements to include (in addition to Panel).

  • js_resources ('auto' | List[str]) – The list of JS resources to include in the exported HTML.

  • css_resources ('auto' | List[str] | None) – The list of CSS resources to include in the exported HTML.

  • runtime ('pyodide' | 'pyscript') – The runtime to use for running Python in the browser.

  • prerender (bool) – Whether to pre-render the components so the page loads.

  • panel_version ('auto' | str) – The panel release version to use in the exported HTML.

  • http_patch (bool) – Whether to patch the HTTP request stack with the pyodide-http library to allow urllib3 and requests to work.


datamodel Module#

Inheritance diagram of panel.io.datamodel
class panel.io.datamodel.Parameterized(default: Init[T] = Intrinsic, help: str | None = None, serialized: bool | None = None, readonly: bool = False)[source]#

Bases: Property

Accept a Parameterized object.

This property only exists to support type validation, e.g. for “accepts” clauses. It is not serializable itself, and is not useful to add to Bokeh models directly.

accepts(tp: Union[Type[Property[Any]], Property[Any]], converter: Callable[[Property[Any]], T]) Property[T]#

Declare that other types may be converted to this property type.

Parameters
  • tp (Property) – A type that may be converted automatically to this property type.

  • converter (callable) – A function accepting value to perform conversion of the value to this property type.

Returns

self

asserts(fn: Callable[[HasProps, T], bool], msg_or_fn: str | Callable[[HasProps, str, T], None]) Property[T]#

Assert that prepared values satisfy given conditions.

Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a ColumnDataSource all collectively have the same length at all times.

Parameters
  • fn (callable) – A function accepting (obj, value) that returns True if the value passes the assertion, or False otherwise.

  • msg_or_fn (str or callable) – A message to print in case the assertion fails, or a function accepting (obj, name, value) to call in in case the assertion fails.

Returns

self

from_json(json: Any, *, models: Dict[ID, HasProps] | None = None) T#

Convert from JSON-compatible values into a value for this property.

JSON-compatible values are: list, dict, number, string, bool, None

is_valid(value: Any) bool#

Whether the value passes validation

Parameters

value (obj) – the value to validate against this property type

Returns

True if valid, False otherwise

make_descriptors(name: str) List[PropertyDescriptor[T]]#

Return a list of PropertyDescriptor instances to install on a class, in order to delegate attribute access to this property.

Parameters

name (str) – the name of the property these descriptors are for

Returns

list[PropertyDescriptor]

The descriptors returned are collected by the MetaHasProps metaclass and added to HasProps subclasses during class creation.

matches(new: T, old: T) bool#

Whether two parameters match values.

If either new or old is a NumPy array or Pandas Series or Index, then the result of np.array_equal will determine if the values match.

Otherwise, the result of standard Python equality will be returned.

Returns

True, if new and old match, False otherwise

property readonly: bool#

Whether this property is read-only.

Read-only properties may only be modified by the client (i.e., by BokehJS in the browser).

serialize_value(value: T) Any#

Change the value into a JSON serializable format.

property serialized: bool#

Whether the property should be serialized when serializing an object.

This would be False for a “virtual” or “convenience” property that duplicates information already available in other properties, for example.

themed_default(cls: Type[HasProps], name: str, theme_overrides: Dict[str, Any] | None) T#

The default, transformed by prepare_value() and the theme overrides.

transform(value: Any) T#

Change the value into the canonical format for this property.

Parameters

value (obj) – the value to apply transformation to.

Returns

transformed value

Return type

obj

wrap(value: T) T#

Some property types need to wrap their values in special containers, etc.

class panel.io.datamodel.ParameterizedList(default: Init[T] = Intrinsic, help: str | None = None, serialized: bool | None = None, readonly: bool = False)[source]#

Bases: Property

Accept a list of Parameterized objects.

This property only exists to support type validation, e.g. for “accepts” clauses. It is not serializable itself, and is not useful to add to Bokeh models directly.

accepts(tp: Union[Type[Property[Any]], Property[Any]], converter: Callable[[Property[Any]], T]) Property[T]#

Declare that other types may be converted to this property type.

Parameters
  • tp (Property) – A type that may be converted automatically to this property type.

  • converter (callable) – A function accepting value to perform conversion of the value to this property type.

Returns

self

asserts(fn: Callable[[HasProps, T], bool], msg_or_fn: str | Callable[[HasProps, str, T], None]) Property[T]#

Assert that prepared values satisfy given conditions.

Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a ColumnDataSource all collectively have the same length at all times.

Parameters
  • fn (callable) – A function accepting (obj, value) that returns True if the value passes the assertion, or False otherwise.

  • msg_or_fn (str or callable) – A message to print in case the assertion fails, or a function accepting (obj, name, value) to call in in case the assertion fails.

Returns

self

from_json(json: Any, *, models: Dict[ID, HasProps] | None = None) T#

Convert from JSON-compatible values into a value for this property.

JSON-compatible values are: list, dict, number, string, bool, None

is_valid(value: Any) bool#

Whether the value passes validation

Parameters

value (obj) – the value to validate against this property type

Returns

True if valid, False otherwise

make_descriptors(name: str) List[PropertyDescriptor[T]]#

Return a list of PropertyDescriptor instances to install on a class, in order to delegate attribute access to this property.

Parameters

name (str) – the name of the property these descriptors are for

Returns

list[PropertyDescriptor]

The descriptors returned are collected by the MetaHasProps metaclass and added to HasProps subclasses during class creation.

matches(new: T, old: T) bool#

Whether two parameters match values.

If either new or old is a NumPy array or Pandas Series or Index, then the result of np.array_equal will determine if the values match.

Otherwise, the result of standard Python equality will be returned.

Returns

True, if new and old match, False otherwise

property readonly: bool#

Whether this property is read-only.

Read-only properties may only be modified by the client (i.e., by BokehJS in the browser).

serialize_value(value: T) Any#

Change the value into a JSON serializable format.

property serialized: bool#

Whether the property should be serialized when serializing an object.

This would be False for a “virtual” or “convenience” property that duplicates information already available in other properties, for example.

themed_default(cls: Type[HasProps], name: str, theme_overrides: Dict[str, Any] | None) T#

The default, transformed by prepare_value() and the theme overrides.

transform(value: Any) T#

Change the value into the canonical format for this property.

Parameters

value (obj) – the value to apply transformation to.

Returns

transformed value

Return type

obj

validate(value, detail=True)[source]#

Determine whether we can set this property from this value.

Validation happens before transform()

Parameters
  • value (obj) – the value to validate against this property type

  • detail (bool, options) –

    whether to construct detailed exceptions

    Generating detailed type validation error messages can be expensive. When doing type checks internally that will not escape exceptions to users, these messages can be skipped by setting this value to False (default: True)

Returns

None

Raises

ValueError if the value is not valid for this property type

wrap(value: T) T#

Some property types need to wrap their values in special containers, etc.

panel.io.datamodel.construct_data_model(parameterized, name=None, ignore=[], types={})[source]#

Dynamically creates a Bokeh DataModel class from a Parameterized object.

Parameters
  • parameterized (param.Parameterized) – The Parameterized class or instance from which to create the DataModel

  • name (str or None) – Name of the dynamically created DataModel class

  • ignore (list(str)) – List of parameters to ignore.

  • types (dict) – A dictionary mapping from parameter name to a Parameter type, making it possible to override the default parameter types.

Return type

DataModel

panel.io.datamodel.create_linked_datamodel(obj, root=None)[source]#

Creates a Bokeh DataModel from a Parameterized class or instance which automatically links the parameters bi-directionally.

Parameters

obj (param.Parameterized) – The Parameterized class to create a linked DataModel for.

Return type

DataModel instance linked to the Parameterized object.


django Module#


document Module#

Inheritance diagram of panel.io.document
class panel.io.document.MockSessionContext(*args, document=None, **kwargs)[source]#

Bases: SessionContext

property destroyed: bool#

If True, the session has been discarded and cannot be used.

A new session with the same ID could be created later but this instance will not come back to life.

property id: ID#

The unique ID for the session associated with this context.

property server_context: ServerContext#

The server context for this session context

with_locked_document(*args)[source]#

Runs a function with the document lock held, passing the document to the function.

Subclasses must implement this method.

Parameters

func (callable) – function that takes a single parameter (the Document) and returns None or a Future

Returns

a Future containing the result of the function

class panel.io.document.Request(headers: 'dict', cookies: 'dict', arguments: 'dict')[source]#

Bases: object

panel.io.document.unlocked() Iterator[source]#

Context manager which unlocks a Document and dispatches ModelChangedEvents triggered in the context body to all sockets on current sessions.

panel.io.document.with_lock(func: Callable) Callable[source]#

Wrap a callback function to execute with a lock allowing the function to modify bokeh models directly.

Parameters

func (callable) – The callable to wrap

Returns

wrapper – Function wrapped to execute without a Document lock.

Return type

callable


embed Module#

Various utilities for recording and embedding state in a rendered app.

panel.io.embed.embed_state(panel, model, doc, max_states=1000, max_opts=3, json=False, json_prefix='', save_path='./', load_path=None, progress=True, states={})[source]#

Embeds the state of the application on a State model which allows exporting a static version of an app. This works by finding all widgets with a predefined set of options and evaluating the cross product of the widget values and recording the resulting events to be replayed when exported. The state is recorded on a State model which is attached as an additional root on the Document.

Parameters
  • panel (panel.reactive.Reactive) – The Reactive component being exported

  • model (bokeh.model.Model) – The bokeh model being exported

  • doc (bokeh.document.Document) – The bokeh Document being exported

  • max_states (int (default=1000)) – The maximum number of states to export

  • max_opts (int (default=3)) – The max number of ticks sampled in a continuous widget like a slider

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

Converts links declared in Python into JS Links by using the declared forward and reverse JS transforms on the source and target.

Converts Param pane widget links into JS links if possible.


ipywidget Module#

Inheritance diagram of panel.io.ipywidget
class panel.io.ipywidget.MessageSentBuffers(_typename, _fields=None, /, **kwargs)[source]#

Bases: dict

clear() None.  Remove all items from D.#
copy() a shallow copy of D#
fromkeys(value=None, /)#

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)#

Return the value for key if key is in the dictionary, else default.

items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, default is returned if given, otherwise KeyError is raised

popitem()#

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)#

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.#

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values#
class panel.io.ipywidget.MessageSentEventPatched(document: Document, msg_type: str, msg_data: Union[Any, bytes], setter: Setter | None = None, callback_invoker: Invoker | None = None)[source]#

Bases: MessageSentEvent

Patches MessageSentEvent with fix that ensures MessageSent event does not define msg_data (which is an assumption in BokehJS Document.apply_json_patch.)

combine(event: DocumentChangedEvent) bool#
dispatch(receiver: Any) None#

Dispatch handling of this event to a receiver.

This method will invoke receiver._document_patched if it exists.

generate(references, buffers)[source]#

Create a JSON representation of this event suitable for sending to clients.

Sub-classes must implement this method.

Parameters
  • references (dict[str, Model]) –

    If the event requires references to certain models in order to function, they may be collected here.

    This is an “out” parameter. The values it contains will be modified in-place.

  • buffers (set) –

    If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set.

    This is an “out” parameter. The values it contains will be modified in-place.

static handle_json(doc: Document, event_json: DocumentPatched, references: List[ReferenceJson], setter: Setter) None#
class panel.io.ipywidget.PanelKernel(**kwargs: Any)[source]#

Bases: BokehKernel

async abort_request(stream, ident, parent)#

abort a specific msg by id

add_traits(**traits)#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc()#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes=None)#

Get the config section for this class.

Parameters

classes (list, optional) – The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst=None)#

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, inst=None, helptext=None)#

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

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

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

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

classmethod class_trait_names(**metadata)#

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

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

unset _instance for this class and singleton parents.

async clear_request(stream, idents, parent)#

Clear our namespace.

property cross_validation_lock#

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.

async dispatch_queue()#

Coroutine to preserve order of message handling

Ensures that only one message is processing at a time, even when the handler is async

async dispatch_shell(msg)#

dispatch shell requests

do_apply(content, bufs, msg_id, reply_metadata)#

DEPRECATED

do_clear()#

DEPRECATED since 4.0.3

do_complete(code, cursor_pos)#

Override in subclasses to find completions.

do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_id=None)#

Execute user code. Must be overridden by subclasses.

do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)#

Override in subclasses to access history.

do_inspect(code, cursor_pos, detail_level=0, omit_sections=())#

Override in subclasses to allow introspection.

do_is_complete(code)#

Override in subclasses to find completions.

async do_one_iteration()#

Process a single shell message

Any pending control messages will be flushed as well

Changed in version 5: This is now a coroutine

do_shutdown(restart)#

Override in subclasses to do things when the frontend shuts down the kernel.

enter_eventloop()#

enter eventloop

async execute_request(stream, ident, parent)#

handle an execute_request

finish_metadata(parent, metadata, reply_content)#

Finish populating metadata.

Run after completing an execution request.

get_parent(channel='shell')#

Get the parent request associated with a channel.

New in version 6.

Parameters

channel (str) – the name of the channel (‘shell’ or ‘control’)

Returns

message – the parent message for the most recent request on the channel.

Return type

dict

getpass(prompt='', stream=None)#

Forward getpass to frontends

Raises

StdinNotImplementedError if active frontend doesn't support stdin.

has_trait(name)#

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

hold_trait_notifications()#

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.

init_metadata(parent)#

Initialize metadata.

Run at the beginning of execution requests.

classmethod initialized()#

Has an instance been created?

classmethod instance(*args, **kwargs)#

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 retrived using the base class instance:

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

Notify observers of a change event

observe(handler, names=traitlets.All, type='change')#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters
  • handler (callable) – 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.

  • names (list, 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.

  • type (str, 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=None, name=None, remove=False)#

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
  • handler (callable, 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).

  • name (list, 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.

  • remove (bool) – If False (the default), then install the handler. If True then unintall it.

post_handler_hook()#

Hook to execute after calling message handler

pre_handler_hook()#

Hook to execute before calling message handler

async process_control(msg)#

dispatch control requests

async process_one(wait=True)#

Process one request

Returns None if no message was handled.

raw_input(prompt='')#

Forward raw_input to frontends

Raises

StdinNotImplementedError if active frontend doesn't support stdin.

record_ports(ports)#

Record the ports that this kernel is using.

The creator of the Kernel instance must call this methods if they want the connect_request() method to return the port numbers.

schedule_dispatch(dispatch, *args)#

schedule a message for dispatch

classmethod section_names()#

return section names as a list

send_response(stream, msg_or_type, content=None, ident=None, buffers=None, track=False, header=None, metadata=None, channel='shell')#

Send a response to the message we’re currently processing.

This accepts all the parameters of jupyter_client.session.Session.send() except parent.

This relies on set_parent() having been called for the current message.

set_parent(ident, parent, channel='shell')#

Set the current parent request

Side effects (IOPub messages) and replies are associated with the request that caused them via the parent_header.

The parent identity is used to route input_request messages on the stdin channel.

set_trait(name, value)#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs)#

This is called before self.__init__ is called.

should_handle(stream, msg, idents)#

Check whether a shell-channel message should be handled

Allows subclasses to prevent handling of certain messages (e.g. aborted requests).

start()#

register dispatchers for streams

trait_defaults(*names, **metadata)#

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

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

Parameters

name (str (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.

Return type

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

trait_has_value(name)#

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, key, default=None)#

Get metadata values for trait by key.

trait_names(**metadata)#

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

trait_values(**metadata)#

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.

Return type

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

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, names=traitlets.All, type='change')#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters
  • handler (callable) – The callable called when a trait attribute changes.

  • names (list, 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.

  • type (str 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=traitlets.All)#

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

update_config(config)#

Update config and load the new values

class panel.io.ipywidget.PanelSessionWebsocket(**kwargs: Any)[source]#

Bases: SessionWebsocket

add_traits(**traits)#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_config_rst_doc()#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes=None)#

Get the config section for this class.

Parameters

classes (list, optional) – The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst=None)#

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, inst=None, helptext=None)#

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

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

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

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

classmethod class_trait_names(**metadata)#

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

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.

clone()#

Create a copy of this Session

Useful when connecting multiple times to a given kernel. This prevents a shared digest_history warning about duplicate digests due to multiple connections to IOPub in the same process.

New in version 5.1.

property cross_validation_lock#

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.

deserialize(msg_list, content=True, copy=True)#

Unserialize a msg_list to a nested message dict.

This is roughly the inverse of serialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.

Parameters
  • msg_list (list of bytes or Message objects) – The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,…].

  • content (bool (True)) – Whether to unpack the content dict (True), or leave it packed (False).

  • copy (bool (True)) – Whether msg_list contains bytes (True) or the non-copying Message objects in each place (False).

Returns

msg – The nested message dict with top-level keys [header, parent_header, content, buffers]. The buffers are returned as memoryviews.

Return type

dict

feed_identities(msg_list, copy=True)#

Split the identities from the rest of the message.

Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly.

Parameters
  • msg_list (a list of Message or bytes objects) – The message to be split.

  • copy (bool) – flag determining whether the arguments are bytes or Messages

Returns

(idents, msg_list) – idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,…] and should be unpackable/unserializable via self.deserialize at this point.

Return type

two lists

has_trait(name)#

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

hold_trait_notifications()#

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.

msg(msg_type, content=None, parent=None, header=None, metadata=None)#

Return the nested message dict.

This format is different from what is sent over the wire. The serialize/deserialize methods converts this nested message dict to the wire format, which is a list of message parts.

notify_change(change)#

Notify observers of a change event

observe(handler, names=traitlets.All, type='change')#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters
  • handler (callable) – 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.

  • names (list, 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.

  • type (str, 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=None, name=None, remove=False)#

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
  • handler (callable, 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).

  • name (list, 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.

  • remove (bool) – If False (the default), then install the handler. If True then unintall it.

recv(socket, mode=Flag.DONTWAIT, content=True, copy=True)#

Receive and unpack a message.

Parameters

socket (ZMQStream or Socket) – The socket or stream to use in receiving.

Returns

[idents] is a list of idents and msg is a nested message dict of same format as self.msg returns.

Return type

[idents], msg

classmethod section_names()#

return section names as a list

send(stream, msg_type, content=None, parent=None, ident=None, buffers=None, track=False, header=None, metadata=None)[source]#

Build and send a message via stream or socket.

The message format used by this function internally is as follows:

[ident1,ident2,…,DELIM,HMAC,p_header,p_parent,p_content,

buffer1,buffer2,…]

The serialize/deserialize methods convert the nested message dict into this format.

Parameters
  • stream (zmq.Socket or ZMQStream) – The socket-like object used to send the data.

  • msg_or_type (str or Message/dict) – Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header.

  • content (dict or None) – The content of the message (ignored if msg_or_type is a message).

  • header (dict or None) – The header dict for the message (ignored if msg_to_type is a message).

  • parent (Message or dict or None) – The parent or parent header describing the parent of this message (ignored if msg_or_type is a message).

  • ident (bytes or list of bytes) – The zmq.IDENTITY routing path.

  • metadata (dict or None) – The metadata describing the message

  • buffers (list or None) – The already-serialized buffers to be appended to the message.

  • track (bool) – Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages.

Returns

msg – The constructed message.

Return type

dict

send_raw(stream, msg_list, flags=0, copy=True, ident=None)#

Send a raw message via ident path.

This method is used to send a already serialized message.

Parameters
  • stream (ZMQStream or Socket) – The ZMQ stream or socket to use for sending the message.

  • msg_list (list) – The serialized list of messages to send. This only includes the [p_header,p_parent,p_metadata,p_content,buffer1,buffer2,…] portion of the message.

  • ident (ident or list) – A single ident or a list of idents to use in sending.

serialize(msg, ident=None)#

Serialize the message components to bytes.

This is roughly the inverse of deserialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.

Parameters

msg (dict or Message) – The next message dict as returned by the self.msg method.

Returns

msg_list

The list of bytes objects to be sent with the format:

[ident1, ident2, ..., DELIM, HMAC, p_header, p_parent,
 p_metadata, p_content, buffer1, buffer2, ...]

In this list, the p_* entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings.

Return type

list

set_trait(name, value)#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs)#

This is called before self.__init__ is called.

sign(msg_list)#

Sign a message with HMAC digest. If no auth, return b’’.

Parameters

msg_list (list) – The [p_header,p_parent,p_content] part of the message list.

trait_defaults(*names, **metadata)#

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

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

Parameters

name (str (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.

Return type

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

trait_has_value(name)#

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, key, default=None)#

Get metadata values for trait by key.

trait_names(**metadata)#

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

trait_values(**metadata)#

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.

Return type

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

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, names=traitlets.All, type='change')#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters
  • handler (callable) – The callable called when a trait attribute changes.

  • names (list, 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.

  • type (str 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=traitlets.All)#

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

update_config(config)#

Update config and load the new values


jupyter_server_extension Module#

Inheritance diagram of panel.io.jupyter_server_extension

The Panel jupyter_server_extension implements Jupyter RequestHandlers that allow a Panel application to run inside Jupyter kernels. This allows Panel applications to be served in the kernel (and therefore the environment) they were written for.

The PanelJupyterHandler may be given the path to a notebook, .py file or Lumen .yaml file. It will then attempt to resolve the appropriate kernel based on the kernelspec or a query parameter. Once the kernel has been provisioned the handler will execute a code snippet on the kernel which creates a PanelExecutor. The PanelExecutor creates a bokeh.server.session.ServerSession and connects it to a Jupyter Comm. The PanelJupyterHandler will then serve the result of executor.render().

Once the frontend has rendered the HTML it will send a request to open a WebSocket will be sent to the PanelWSProxy. This in turns forwards any messages it receives via the kernel.shell_channel and the Comm to the PanelExecutor. This way we proxy any WS messages being sent to and from the server to the kernel.

class panel.io.jupyter_server_extension.PanelExecutor(path, token, root_url)[source]#

Bases: WSHandler

The PanelExecutor is intended to be run inside a kernel where it runs a Panel application renders the HTML and then establishes a Jupyter Comm channel to communicate with the PanelWSProxy in order to send and receive messages to and from the frontend.

add_header(name: str, value: Union[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.

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_origin(origin: str) bool#

Implement a check_origin policy for Tornado to call.

The supplied origin will be compared to the Bokeh server allowlist. If the origin is not allow, an error will be logged and False will be returned.

Parameters

origin (str) – The URL of the connection origin

Returns

bool, True if the connection is allowed, False otherwise

Verifies that the _xsrf cookie matches the _xsrf argument.

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

The _xsrf value may be set as either a form field named _xsrf or in a custom HTTP header named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

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

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None#

Resets all headers and content for this response.

clear_all_cookies(path: str = '/', domain: Optional[str] = None) None#

Deletes all the cookies the user sent with this request.

See clear_cookie for more information on the path and domain parameters.

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.

Deletes the cookie with the given name.

Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie).

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

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.

close(code: Optional[int] = None, reason: Optional[str] = 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.

classmethod code(path: str, token: str, root_url: str) str[source]#

Generates the code to instantiate a PanelExecutor that is to be be run on the kernel to start a server session.

Parameters
  • path (str) – The path of the Panel application to execute.

  • token (str) – The Bokeh JWT token containing the session_id, request arguments, headers and cookies.

  • root_url (str) – The root_url the server is running on.

Return type

The code to be executed inside the kernel.

compute_etag() Optional[str]#

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 cookies: Dict[str, Morsel]#

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

create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_secure_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_secure_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_secure_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_secure_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) Optional[Awaitable[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: Optional[str] = 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.

New in version 5.1.

finish(chunk: Optional[Union[str, bytes, dict]] = 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.

get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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

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

Delegate to the synchronous get_user method of the auth provider

get_login_url()#

Delegates to``get_login_url`` method of the auth provider, or the login_url attribute.

get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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_secure_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.

Returns the signing key version of the secure cookie.

The version is returned as int.

get_status() int#

Returns the status code for our response.

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() Optional[str]#

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() Optional[Locale]#

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(application_context, bokeh_websocket_path)#
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.

log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) 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).

New in version 3.1.

property max_message_size: int#

Maximum allowed message size.

If the remote peer sends a message larger than this, the connection will be closed.

Default is 10MiB.

on_close() None#

Clean up when the connection is closed.

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(fragment: str | bytes) None#

Process an individual wire protocol fragment.

The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got.

Parameters

fragment (unicode or bytes) – wire fragment to process

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.

open() None#

Initialize a connection to a client.

Returns

None

ping(data: Union[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: Optional[float]#

The interval for websocket keep-alive pings.

Set websocket_ping_interval = 0 to disable pings.

property ping_timeout: Optional[float]#

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

Async counterpart to get_current_user

redirect(url: str, permanent: bool = False, status: Optional[int] = 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() HTML[source]#

Renders the application to an IPython.display.HTML object to be served by the PanelJupyterHandler.

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.

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: Optional[str]#

The subprotocol returned by select_subprotocol.

New in version 5.1.

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.

async send_message(message: Message[Any]) None#

Send a Bokeh Server protocol message to the connected client.

Parameters

message (Message) – a message to send

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.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object.

Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes.

set_default_headers() None#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

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: Union[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.

New 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_secure_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_secure_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.

set_status(status_code: int, reason: Optional[str] = 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>.

static_url(path: str, include_host: Optional[bool] = 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.

write(chunk: Union[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 https://github.com/facebook/tornado/issues/1009

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

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

async write_message(message: Union[bytes, str, Dict[str, Any]], binary: bool = False, locked: bool = True) None[source]#

Override parent write_message with a version that acquires a write lock before writing.

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 panel.io.jupyter_server_extension.PanelJupyterHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: JupyterHandler

The PanelJupyterHandler expects to be given a path to a notebook, .py file or Lumen .yaml file. Based on the kernelspec in the notebook or the kernel query parameter it will then provision a Jupyter kernel to run the Panel application in.

Once the kernel is launched it will instantiate a PanelExecutor inside the kernel and serve the HTML returned by it. If successful it will store the kernel and comm_id on panel.state.

add_header(name: str, value: Union[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#

Whether to set Access-Control-Allow-Credentials

property allow_origin#

Normal Access-Control-Allow-Origin

property allow_origin_pat#

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

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado='')#

Check Origin for cross-site API requests, including websockets

Copied from WebSocket with changes:

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

  • allow token-authenticated requests

check_referer()#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(path: str = '/', domain: Optional[str] = None) None#

Deletes all the cookies the user sent with this request.

See clear_cookie for more information on the path and domain parameters.

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.

Deletes the cookie with the given name.

Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie).

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

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.

compute_etag() Optional[str]#

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#

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: Union[str, bytes], version: Optional[int] = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_secure_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_secure_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_secure_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_secure_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) Optional[Awaitable[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: Optional[str] = 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.

New in version 5.1.

finish(chunk: Optional[Union[str, bytes, dict]] = 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.

get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

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

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_json_body()#

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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_secure_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.

Returns the signing key version of the secure cookie.

The version is returned as int.

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() Optional[str]#

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() Optional[Locale]#

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(**kwargs)[source]#
property jinja_template_vars#

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#

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

log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) 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).

New in version 3.1.

property logged_in#

Is a user currently logged in?

property login_available#

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#

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.

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.

New in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: Optional[int] = 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.

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

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.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object.

Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes.

set_cors_headers()#

Add CORS headers, if defined

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

set_default_headers()#

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: Union[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_secure_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_secure_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.

set_status(status_code: int, reason: Optional[str] = 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()#

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: Optional[bool] = 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#

Return the login token for this application, if any.

property token_authenticated#

Have I been authenticated with a token?

property version_hash#

The version hash to use for cache hints for static files

write(chunk: Union[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 https://github.com/facebook/tornado/issues/1009

write_error(status_code, **kwargs)#

render custom error 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 panel.io.jupyter_server_extension.PanelWSProxy(tornado_app, *args, **kw)[source]#

Bases: WSHandler, JupyterHandler

The PanelWSProxy serves as a proxy between the frontend and the Jupyter kernel that is running the Panel application. It send and receives Bokeh protocol messages via a Jupyter Comm.

add_header(name: str, value: Union[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#

Whether to set Access-Control-Allow-Credentials

property allow_origin#

Normal Access-Control-Allow-Origin

property allow_origin_pat#

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

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin: str) bool[source]#

Implement a check_origin policy for Tornado to call.

The supplied origin will be compared to the Bokeh server allowlist. If the origin is not allow, an error will be logged and False will be returned.

Parameters

origin (str) – The URL of the connection origin

Returns

bool, True if the connection is allowed, False otherwise

check_referer()#

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

Bypass xsrf cookie checks when token-authenticated

clear() None#

Resets all headers and content for this response.

clear_all_cookies(path: str = '/', domain: Optional[str] = None) None#

Deletes all the cookies the user sent with this request.

See clear_cookie for more information on the path and domain parameters.

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.

Deletes the cookie with the given name.

Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie).

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

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.

close(code: Optional[int] = None, reason: Optional[str] = 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() Optional[str]#

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#

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: Union[str, bytes], version: Optional[int] = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_secure_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_secure_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_secure_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_secure_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) Optional[Awaitable[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: Optional[str] = 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.

New in version 5.1.

finish(chunk: Optional[Union[str, bytes, dict]] = 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.

get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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

New 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()[source]#

Delegate to the synchronous get_user method of the auth provider

get_json_body()#

Return the body of the request as JSON data.

get_login_url()#

Delegates to``get_login_url`` method of the auth provider, or the login_url attribute.

get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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_secure_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.

Returns the signing key version of the secure cookie.

The version is returned as int.

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() Optional[str]#

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() Optional[Locale]#

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(*args, **kwargs)[source]#
property jinja_template_vars#

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#

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

log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) 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).

New in version 3.1.

property logged_in#

Is a user currently logged in?

property login_available#

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#

Return the login handler for this application, if any.

property max_message_size: int#

Maximum allowed message size.

If the remote peer sends a message larger than this, the connection will be closed.

Default is 10MiB.

on_close() None[source]#

Clean up when the connection is closed.

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(fragment: str | bytes) None[source]#

Process an individual wire protocol fragment.

The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got.

Parameters

fragment (unicode or bytes) – wire fragment to process

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.

open(path, *args, **kwargs) None[source]#

Initialize a connection to a client.

Returns

None

ping(data: Union[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: Optional[float]#

The interval for websocket keep-alive pings.

Set websocket_ping_interval = 0 to disable pings.

property ping_timeout: Optional[float]#

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()[source]#

Async counterpart to get_current_user

redirect(url: str, permanent: bool = False, status: Optional[int] = 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.

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: Optional[str]#

The subprotocol returned by select_subprotocol.

New in version 5.1.

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.

async send_message(message: Message[Any]) None#

Send a Bokeh Server protocol message to the connected client.

Parameters

message (Message) – a message to send

set_attachment_header(filename)#

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.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object.

Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes.

set_cors_headers()#

Add CORS headers, if defined

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

set_default_headers()#

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: Union[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.

New 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_secure_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_secure_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.

set_status(status_code: int, reason: Optional[str] = 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()#

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: Optional[bool] = 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#

Return the login token for this application, if any.

property token_authenticated#

Have I been authenticated with a token?

property version_hash#

The version hash to use for cache hints for static files

write(chunk: Union[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 https://github.com/facebook/tornado/issues/1009

write_error(status_code, **kwargs)#

render custom error pages

async write_message(message: Union[bytes, str, Dict[str, Any]], binary: bool = False, locked: bool = True) None#

Override parent write_message with a version that acquires a write lock before writing.

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.

async panel.io.jupyter_server_extension.ensure_async(obj: Union[Awaitable, Any]) Any[source]#

Convert a non-awaitable object to a coroutine if needed, and await it if it was not already awaited.

panel.io.jupyter_server_extension.url_path_join(*pieces)[source]#

Join components of url into a relative url Use to prevent double slash when joining subpath. This will leave the initial and final / in place


liveness Module#

Inheritance diagram of panel.io.liveness
class panel.io.liveness.LivenessHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

add_header(name: str, value: Union[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.

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.

Verifies that the _xsrf cookie matches the _xsrf argument.

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

The _xsrf value may be set as either a form field named _xsrf or in a custom HTTP header named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

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

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None#

Resets all headers and content for this response.

clear_all_cookies(path: str = '/', domain: Optional[str] = None) None#

Deletes all the cookies the user sent with this request.

See clear_cookie for more information on the path and domain parameters.

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.

Deletes the cookie with the given name.

Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie).

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

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.

compute_etag() Optional[str]#

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 cookies: Dict[str, Morsel]#

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

create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes#

Signs and timestamps a string so it cannot be forged.

Normally used via set_secure_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_secure_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_secure_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_secure_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) Optional[Awaitable[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: Optional[str] = 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.

New in version 5.1.

finish(chunk: Optional[Union[str, bytes, dict]] = 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.

get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

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

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

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: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str]#

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.

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

New 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_secure_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.

Returns the signing key version of the secure cookie.

The version is returned as int.

get_status() int#

Returns the status code for our response.

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() Optional[str]#

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() Optional[Locale]#

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(applications)[source]#
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.

log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) 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).

New in version 3.1.

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.

prepare() Optional[Awaitable[None]]#

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.

New in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: Optional[int] = 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