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(*, callback, count, counter, log, period, running, timeout, name)[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, allow_refs=False, label=’Callback’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14207ecd0>)

The callback to execute periodically.

counter = param.Integer(allow_refs=False, default=0, inclusive_bounds=(True, True), label=’Counter’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14220b9d0>)

Counts the number of executions.

count = param.Integer(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Count’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1427445d0>)

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

log = param.Boolean(allow_refs=False, default=True, label=’Log’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142740f90>)

Whether the periodic callback should log its actions.

period = param.Integer(allow_refs=False, default=500, inclusive_bounds=(True, True), label=’Period’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142744610>)

Period in milliseconds at which the callback is executed.

timeout = param.Integer(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Timeout’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142744cd0>)

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

running = param.Boolean(allow_refs=False, default=False, label=’Running’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14276bd90>)

Toggles whether the periodic callback is currently running.

start()[source]#

Starts running the periodic callback.

stop()[source]#

Stops running the periodic callback.

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

Bases: Resources

adjust_paths(resources)[source]#

Computes relative and absolute paths for resources.

clone(*, components=None) Resources[source]#

Make a clone of a resources instance allowing to override its components.

extra_resources(resources, resource_type)[source]#

Adds resources for ReactiveHTML components.

panel.io.hold(doc: Document | None = None, policy: HoldPolicyType = 'combine', comm: Comm | None = None)[source]#

Context manager that holds events on a particular Document allowing them all to be collected and dispatched when the context manager exits. This allows multiple events on the same object to be combined if the policy is set to ‘combine’.

Arguments#

doc: Document

The Bokeh Document to hold events on.

policy: HoldPolicyType

One of ‘combine’, ‘collect’ or None determining whether events setting the same property are combined or accumulated to be dispatched when the context manager exits.

comm: Comm

The Comm to dispatch events on when the context manager exits.

panel.io.immediate_dispatch(doc: Document | None = None)[source]#

Context manager to trigger immediate dispatch of events triggered inside the execution context even when Document events are currently on hold.

Arguments#

doc: Document

The document to dispatch events on (if None then state.curdoc is used).

panel.io.ipywidget(obj: Any, doc=None, **kwargs: Any)[source]#

Returns an ipywidget model which renders the Panel object.

Requires jupyter_bokeh to be installed.

Arguments#

obj: object

Any Panel object or object which can be rendered with Panel

doc: bokeh.Document

Bokeh document the bokeh model will be attached to.

**kwargs: dict

Keyword arguments passed to the pn.panel utility function

Returns#

Returns an ipywidget model which renders the Panel object.

panel.io.profile(name: str, engine: ProfilingEngine = 'pyinstrument') Callable[[Callable[_P, _R]], Callable[_P, _R]][source]#

A decorator which may be added to any function to record profiling output.

Arguments#

name: str

A unique name for the profiling session.

engine: str

The profiling engine, e.g. ‘pyinstrument’, ‘snakeviz’ or ‘memray’

panel.io.push(doc: Document, comm: Comm, binary: bool = True, msg: any = None) 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.

Arguments#

objs: panel.viewable.Viewable

panel.io.serve(panels: TViewableFuncOrPath | Mapping[str, TViewableFuncOrPath], port: int = 0, address: str | None = None, websocket_origin: str | list[str] | None = None, loop: IOLoop | None = None, show: bool = True, start: bool = True, title: str | None = None, verbose: bool = True, location: bool = True, threaded: bool = False, admin: bool = False, **kwargs) StoppableThread | 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/Server_Configuration.html#serving-multiple-apps

Arguments#

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

addressstr

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.

looptornado.ioloop.IOLoop (optional, default=IOLoop.current())

The tornado IOLoop to run the Server on

showboolean (optional, default=True)

Whether to open the server in a new browser tab on start

startboolean(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

locationboolean 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(policy: HoldPolicyType = 'combine') Iterator[source]#

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

Arguments#

policy: Literal[‘combine’ | ‘collect’]

One of ‘combine’ or ‘collect’ determining whether events setting the same property are combined or accumulated to be dispatched when the context manager exits.

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.

Arguments#

func: callable

The callable to wrap

Returns#

wrapper: callable

Function wrapped to execute without a Document lock.


admin Module#

class panel.io.admin.Data(*, data, name)[source]#

Bases: Parameterized

data = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Data’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142a21bd0>)

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

Bases: StreamHandler

acquire()[source]#

Acquire the I/O thread lock.

addFilter(filter)[source]#

Add the specified filter to this handler.

close()[source]#

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

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

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

Flushes the stream.

format(record)[source]#

Format the specified record.

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

handle(record)[source]#

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

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

Release the I/O thread lock.

removeFilter(filter)[source]#

Remove the specified filter from this handler.

setFormatter(fmt)[source]#

Set the formatter for this handler.

setLevel(level)[source]#

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

setStream(stream)[source]#

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.


application Module#

Extensions for Bokeh application handling.

class panel.io.application.Application(*args, **kwargs)[source]#

Bases: Application

Extends Bokeh Application with ability to add global session creation callbacks, support for the admin dashboard and the ability to globally define a template.

add(handler: Handler) None[source]#

Override default DocumentLifeCycleHandler

create_document() Document[source]#

Creates and initializes a document using the Application’s handlers.

property handlers: tuple[Handler, ...]#

The ordered list of handlers this Application is configured with.

initialize_document(doc)[source]#

Fills in a new document using the Application’s handlers.

property metadata: dict[str, Any] | None#

Arbitrary user-supplied metadata to associate with this application.

on_server_loaded(server_context: ServerContext) None[source]#

Invoked to execute code when a new session is created.

This method calls on_server_loaded on each handler, in order, with the server context passed as the only argument.

on_server_unloaded(server_context: ServerContext) None[source]#

Invoked to execute code when the server cleanly exits. (Before stopping the server’s IOLoop.)

This method calls on_server_unloaded on each handler, in order, with the server context passed as the only argument.

Warning

In practice this code may not run, since servers are often killed by a signal.

async on_session_created(session_context)[source]#

Invoked to execute code when a new session is created.

This method calls on_session_created on each handler, in order, with the session context passed as the only argument.

May return a Future which will delay session creation until the Future completes.

async on_session_destroyed(session_context: SessionContext) None[source]#

Invoked to execute code when a session is destroyed.

This method calls on_session_destroyed on each handler, in order, with the session context passed as the only argument.

Afterwards, session_context.destroyed will be True.

process_request(request) dict[str, Any][source]#

Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.

Args:

request: HTTP request

Returns:

A dictionary of JSON serializable data to be included on the session context.

property safe_to_fork: bool#
property static_path: str | None#

Path to any (optional) static resources specified by handlers.

panel.io.application.build_applications(panel: TViewableFuncOrPath | Mapping[str, TViewableFuncOrPath], title: str | dict[str, str] | None = None, location: bool | Location = True, admin: bool = False, server_id: str | None = None, custom_handlers: list | None = None) dict[str, Application][source]#

Converts a variety of objects into a dictionary of Applications.

Arguments#

panel: Viewable, function or {str: Viewable}

A Panel object, a function returning a Panel object or a dictionary mapping from the URL slug to either.

titlestr or {str: str} (optional, default=None)

An HTML title for the application or a dictionary mapping from the URL slug to a customized title.

locationboolean or panel.io.location.Location

Whether to create a Location component to observe and set the URL location.

admin: boolean (default=False)

Whether to enable the admin panel

server_id: str

ID of the server running the application(s)


browser Module#

Defines a BrowserInfo component exposing the browser window and navigator APIs.

class panel.io.browser.BrowserInfo(*, dark_mode, device_pixel_ratio, language, timezone, timezone_offset, webdriver, webgl, name)[source]#

Bases: Syncable

The Location component can be made available in a server context to provide read and write access to the URL components in the browser.

dark_mode = param.Boolean(allow_None=True, allow_refs=False, label=’Dark mode’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142919c90>)

Whether the user prefers dark mode.

device_pixel_ratio = param.Number(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Device pixel ratio’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142bccbd0>)

Provides the ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device.

language = param.String(allow_None=True, allow_refs=False, label=’Language’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142b5a5d0>)

The preferred language of the user, usually the language of the browser UI.

timezone = param.String(allow_None=True, allow_refs=False, label=’Timezone’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142b59890>)

The timezone configured as the local timezone of the user.

timezone_offset = param.Number(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Timezone offset’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142b5b350>)

The time offset from UTC in minutes.

webdriver = param.Boolean(allow_None=True, allow_refs=False, label=’Webdriver’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142b5b010>)

Indicates whether the user agent is controlled by automation.

webgl = param.Boolean(allow_None=True, allow_refs=False, label=’Webgl’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142b5a8d0>)

Indicates whether the browser has WebGL support.

get_root(doc: Document | None = None, comm: Comm | None = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Arguments#

doc: bokeh.Document

Bokeh document the bokeh model will be attached to.

comm: pyviz_comms.Comm

Optional pyviz_comms when working in notebook

preprocess: boolean (default=True)

Whether to run preprocessing hooks

Returns#

Returns the bokeh model corresponding to this panel object


cache Module#

Implements memoization for functions with arbitrary arguments

panel.io.cache.cache(func: Literal[None] = None, hash_funcs: dict[type[Any], Callable[[Any], bytes]] | None = None, max_items: int | None = None, policy: Literal['FIFO', 'LRU', 'LFU'] = 'LRU', ttl: float | None = None, to_disk: bool = False, cache_path: str | PathLike = './cache', per_session: bool = False) Callable[[Callable[_P, _R]], _CachedFunc[Callable[_P, _R]]][source]#
panel.io.cache.cache(func: Callable[_P, _R], hash_funcs: dict[type[Any], Callable[[Any], bytes]] | None = None, max_items: int | None = None, policy: Literal['FIFO', 'LRU', 'LFU'] = 'LRU', ttl: float | None = None, to_disk: bool = False, cache_path: str | PathLike = './cache', per_session: bool = False) _CachedFunc[Callable[_P, _R]]

Memoizes functions for a user session. Can be used as function annotation or just directly.

For global caching across user sessions use pn.state.as_cached.

Arguments#

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.

max_items: int or None

The maximum items to keep in the cache. Default is None, which does not limit number of items stored in the cache.

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

Directory to cache to on disk.

per_session: bool

Whether to cache data only for the current session.

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

Computes a hash given a function and its arguments.

Arguments#

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

panel.io.cache.is_equal(value, other) bool[source]#

Returns True if value and other are equal

Supports complex values like DataFrames


callbacks Module#

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

class panel.io.callbacks.PeriodicCallback(*, callback, count, counter, log, period, running, timeout, name)[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, allow_refs=False, label=’Callback’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142d329d0>)

The callback to execute periodically.

counter = param.Integer(allow_refs=False, default=0, inclusive_bounds=(True, True), label=’Counter’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ac4150>)

Counts the number of executions.

count = param.Integer(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Count’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ad3fd0>)

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

log = param.Boolean(allow_refs=False, default=True, label=’Log’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ac4050>)

Whether the periodic callback should log its actions.

period = param.Integer(allow_refs=False, default=500, inclusive_bounds=(True, True), label=’Period’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ac4210>)

Period in milliseconds at which the callback is executed.

timeout = param.Integer(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Timeout’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ad3dd0>)

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

running = param.Boolean(allow_refs=False, default=False, label=’Running’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142ac4bd0>)

Toggles whether the periodic callback is currently running.

start()[source]#

Starts running the periodic callback.

stop()[source]#

Stops running the periodic callback.


compile Module#

panel.io.compile.compile_components(components: list[type[ReactiveESM]], build_dir: str | PathLike = None, outfile: str | PathLike = None, minify: bool = True, verbose: bool = True) str | None[source]#

Compiles a list of ReactiveESM components into a single JavaScript bundle including their Javascript dependencies.

Arguments#

componentslist[type[ReactiveESM]]

A list of ReactiveESM component classes to compile.

build_dirstr | os.PathLike, optional

The directory where the build output will be saved. If None, a temporary directory will be used.

outfilestr | os.PathLike, optional

The path to the output file where the compiled bundle will be saved. If None the compiled output will be returned.

minifybool, optional

If True, minifies the compiled JavaScript bundle.

verbosebool, optional

If True, prints detailed logs during the compilation process.

Returns#

Returns the compiled bundle or None if outfile is provided.

panel.io.compile.extract_dependencies(component: type[ReactiveESM]) tuple[str, dict[str, any]][source]#

Extracts dependencies from a ReactiveESM component by parsing its importmap and the associated code and replaces URL import specifiers with package imports.

Arguments#

component: type[ReactiveESM]

The ReactiveESM component to extract a dependency definition from.

Returns#

code: str

Code where the URL imports have been replaced by package imports.

dependencies: dict[str, str]

A dictionary of package dependencies and their versions.

panel.io.compile.find_components(module_or_file: str | PathLike, classes: list[str] | None = None) list[type[ReactiveESM]][source]#

Creates a temporary module given a path-like object and finds all the ReactiveESM components defined therein.

Arguments#

module_or_filestr | os.PathLike

The path to the Python module.

classes: list[str] | None

Names of classes to return.

Returns#

List of ReactiveESM components defined in the module.

panel.io.compile.find_module_bundles(module_spec: str) dict[PurePath, list[ReactiveESM]][source]#

Takes module specifications and extracts a set of components to bundle.

Arguments#

module_spec: str

Module specification either as a dotted module or a path to a module.

Returns#

Dictionary containing the bundle paths and list of components to bundle.

panel.io.compile.generate_project(components: list[type[ReactiveESM]], path: str | PathLike, project_config: dict[str, any] = None)[source]#

Converts a set of ESM components into a Javascript project with an index.js, package.json and a T|JS(X) per component.

panel.io.compile.merge_exports(old: ExportSpec, new: ExportSpec)[source]#

Appends the new exports to set of existing ones.

Appropriately combines different kinds of exports including default, import-all exports and named exports.

panel.io.compile.packages_from_code(esm_code: str) dict[str, str][source]#

Extracts package version definitions from ESM code.

Arguments#

esm_codestr

The ESM code to search for package imports.

Returns#

Dictionary of packages and their versions.

panel.io.compile.packages_from_importmap(esm_code: str, imports: dict[str, str]) dict[str, str][source]#

Extracts package version definitions from an import map.

Arguments#

esm_code: str

The ESM code to replace import names in.

importsdict[str, str]

A dictionary representing the import map, where keys are package names and values are URLs.

Returns#

dict[str, str]

A dictionary where keys are package names and values are their corresponding versions.

panel.io.compile.replace_imports(esm_code: str, replacements: dict[str, str]) dict[str, str][source]#

Replaces imports in the code which may be aliases with the actual package names.

Arguments#

esm_code: str

The ESM code to replace import names in.

replacements: dict[str, str]

Mapping that defines replacements from aliased import names to actual package names.

Returns#

modified_code: str

The code where imports have been replaced with package names.


convert Module#

panel.io.convert.convert_apps(apps: str | PathLike | list[str | PathLike], dest_path: str | PathLike | None = None, title: str | None = None, runtime: Literal['pyodide', 'pyscript', 'pyodide-worker', 'pyscript-worker'] = 'pyodide-worker', requirements: list[str] | Literal['auto'] | 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', local_prefix: str = './', http_patch: bool = True, inline: bool = False, compiled: bool = False, 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 | Dict[str, ‘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.
local_prefix: str

Prefix for the path to serve local wheel files from.

http_patch: bool

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

inline: bool

Whether to inline resources.

compiled: bool

Whether to use the compiled and faster version of Pyodide.

panel.io.convert.script_to_html(filename: str | PathLike | IO, requirements: Literal['auto'] | list[str] = 'auto', js_resources: Literal['auto'] | list[str] = 'auto', css_resources: Literal['auto'] | list[str] | None = 'auto', runtime: Literal['pyodide', 'pyscript', 'pyodide-worker', 'pyscript-worker'] = 'pyodide', prerender: bool = True, panel_version: Literal['auto', 'local'] | str = 'auto', local_prefix: str = './', manifest: str | None = None, http_patch: bool = True, inline: bool = False, compiled: bool = True) str[source]#

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

Arguments#

filename: str | Path | IO

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.

local_prefix: str

Prefix for the path to serve local wheel files from.

http_patch: bool

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

inline: bool

Whether to inline resources.

compiled: bool

Whether to use pre-compiled pyodide bundles.


datamodel Module#

class panel.io.datamodel.Parameterized(*, default: T | UndefinedType | IntrinsicType = Intrinsic, help: str | None = None)[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: type[Property[Any]] | Property[Any], converter: Callable[[Any], T]) Property[T][source]#

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

Args:
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][source]#

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.

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

is_valid(value: Any) bool[source]#

Whether the value passes validation

Args:

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

Returns:

True if valid, False otherwise

make_descriptors(name: str) list[PropertyDescriptor[T]][source]#

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

Args:

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

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

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, *, no_eval: bool = False) T[source]#

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

transform(value: Any) T[source]#

Change the value into the canonical format for this property.

Args:

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

Returns:

obj: transformed value

wrap(value: T) T[source]#

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

class panel.io.datamodel.ParameterizedList(*, default: T | UndefinedType | IntrinsicType = Intrinsic, help: str | None = None)[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: type[Property[Any]] | Property[Any], converter: Callable[[Any], T]) Property[T][source]#

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

Args:
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][source]#

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.

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

is_valid(value: Any) bool[source]#

Whether the value passes validation

Args:

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

Returns:

True if valid, False otherwise

make_descriptors(name: str) list[PropertyDescriptor[T]][source]#

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

Args:

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

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

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, *, no_eval: bool = False) T[source]#

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

transform(value: Any) T[source]#

Change the value into the canonical format for this property.

Args:

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

Returns:

obj: transformed value

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

Determine whether we can set this property from this value.

Validation happens before transform()

Args:

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

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

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

Dynamically creates a Bokeh DataModel class from a Parameterized object.

Arguments#

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.

extras: dict

Additional properties to define on the DataModel.

Returns#

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.

Arguments#

obj: param.Parameterized

The Parameterized class to create a linked DataModel for.

Returns#

DataModel instance linked to the Parameterized object.


django Module#


document Module#

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.

Args:
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.freeze_doc(doc: Document, model: HasProps, properties: dict[str, Any], force: bool = False)[source]#

Freezes the document model references if any of the properties are themselves a model.

panel.io.document.hold(doc: Document | None = None, policy: HoldPolicyType = 'combine', comm: Comm | None = None)[source]#

Context manager that holds events on a particular Document allowing them all to be collected and dispatched when the context manager exits. This allows multiple events on the same object to be combined if the policy is set to ‘combine’.

Arguments#

doc: Document

The Bokeh Document to hold events on.

policy: HoldPolicyType

One of ‘combine’, ‘collect’ or None determining whether events setting the same property are combined or accumulated to be dispatched when the context manager exits.

comm: Comm

The Comm to dispatch events on when the context manager exits.

panel.io.document.immediate_dispatch(doc: Document | None = None)[source]#

Context manager to trigger immediate dispatch of events triggered inside the execution context even when Document events are currently on hold.

Arguments#

doc: Document

The document to dispatch events on (if None then state.curdoc is used).

panel.io.document.retrigger_events(doc: Document, events: list[DocumentChangedEvent])[source]#

Applies events that could not be processed previously.

panel.io.document.unlocked(policy: HoldPolicyType = 'combine') Iterator[source]#

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

Arguments#

policy: Literal[‘combine’ | ‘collect’]

One of ‘combine’ or ‘collect’ determining whether events setting the same property are combined or accumulated to be dispatched when the context manager exits.

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.

Arguments#

func: callable

The callable to wrap

Returns#

wrapper: callable

Function wrapped to execute without a Document lock.


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.

Arguments#

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.


fastapi Module#


handlers Module#

class panel.io.handlers.MarkdownHandler(*args, **kwargs)[source]#

Bases: PanelCodeHandler

Modify Bokeh documents by creating Dashboard from a Markdown file.

property error: str | None#

If the handler fails, may contain a related error message.

property error_detail: str | None#

If the handler fails, may contain a traceback or other details.

property failed: bool#

True if the handler failed to modify the doc

modify_document(doc: Document)[source]#

Modify an application document in a specified manner.

When a Bokeh server session is initiated, the Bokeh server asks the Application for a new Document to service the session. To do this, the Application first creates a new empty Document, then it passes this Document to the modify_document method of each of its handlers. When all handlers have updated the Document, it is used to service the user session.

Subclasses must implement this method

Args:

doc (Document) : A Bokeh Document to update in-place

Returns:

Document

on_server_loaded(server_context: ServerContext) None[source]#

Execute code when the server is first started.

Subclasses may implement this method to provide for any one-time initialization that is necessary after the server starts, but before any sessions are created.

Args:

server_context (ServerContext) :

on_server_unloaded(server_context: ServerContext) None[source]#

Execute code when the server cleanly exits. (Before stopping the server’s IOLoop.)

Subclasses may implement this method to provide for any one-time tear down that is necessary before the server exits.

Args:

server_context (ServerContext) :

Warning

In practice this code may not run, since servers are often killed by a signal.

async on_session_created(session_context: SessionContext) None[source]#

Execute code when a new session is created.

Subclasses may implement this method to provide for any per-session initialization that is necessary before modify_doc is called for the session.

Args:

session_context (SessionContext) :

async on_session_destroyed(session_context: SessionContext) None[source]#

Execute code when a session is destroyed.

Subclasses may implement this method to provide for any per-session tear-down that is necessary when sessions are destroyed.

Args:

session_context (SessionContext) :

process_request(request: HTTPServerRequest) dict[str, Any][source]#

Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.

Args:

request: HTTP request

Returns:

A dictionary of JSON serializable data to be included on the session context.

property safe_to_fork: bool#

Whether it is still safe for the Bokeh server to fork new workers.

False if the code has already been executed.

static_path() str | None[source]#

Return a path to app-specific static resources, if applicable.

url_path() str | None[source]#

The last path component for the basename of the configured filename.

class panel.io.handlers.NotebookHandler(*, filename: str | PathLike[str], argv: list[str] = [], package: ModuleType | None = None)[source]#

Bases: PanelCodeHandler

Modify Bokeh documents by creating Dashboard from a notebook file.

property error: str | None#

If the handler fails, may contain a related error message.

property error_detail: str | None#

If the handler fails, may contain a traceback or other details.

property failed: bool#

True if the handler failed to modify the doc

modify_document(doc: Document) None[source]#

Run Bokeh application code to update a Document

Arguments#

doc (Document) : a Document to update

on_server_loaded(server_context: ServerContext) None[source]#

Execute code when the server is first started.

Subclasses may implement this method to provide for any one-time initialization that is necessary after the server starts, but before any sessions are created.

Args:

server_context (ServerContext) :

on_server_unloaded(server_context: ServerContext) None[source]#

Execute code when the server cleanly exits. (Before stopping the server’s IOLoop.)

Subclasses may implement this method to provide for any one-time tear down that is necessary before the server exits.

Args:

server_context (ServerContext) :

Warning

In practice this code may not run, since servers are often killed by a signal.

async on_session_created(session_context: SessionContext) None[source]#

Execute code when a new session is created.

Subclasses may implement this method to provide for any per-session initialization that is necessary before modify_doc is called for the session.

Args:

session_context (SessionContext) :

async on_session_destroyed(session_context: SessionContext) None[source]#

Execute code when a session is destroyed.

Subclasses may implement this method to provide for any per-session tear-down that is necessary when sessions are destroyed.

Args:

session_context (SessionContext) :

process_request(request: HTTPServerRequest) dict[str, Any][source]#

Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.

Args:

request: HTTP request

Returns:

A dictionary of JSON serializable data to be included on the session context.

property safe_to_fork: bool#

Whether it is still safe for the Bokeh server to fork new workers.

False if the code has already been executed.

static_path() str | None[source]#

Return a path to app-specific static resources, if applicable.

url_path() str | None[source]#

The last path component for the basename of the configured filename.

class panel.io.handlers.PanelCodeHandler(*, source: str, filename: str | PathLike[str], argv: list[str] = [], package: ModuleType | None = None)[source]#

Bases: CodeHandler

Modify Bokeh documents by creating Dashboard from code.

Additionally this subclass adds support for the ability to:

  • Log session launch, load and destruction

  • Capture document_ready events to track when app is loaded.

  • Add profiling support

  • Ensure that state.curdoc is set

  • Reload the application module if autoreload is enabled

  • Track modules loaded during app execution to enable autoreloading

property error: str | None#

If the handler fails, may contain a related error message.

property error_detail: str | None#

If the handler fails, may contain a traceback or other details.

property failed: bool#

True if the handler failed to modify the doc

modify_document(doc: Document)[source]#

Modify an application document in a specified manner.

When a Bokeh server session is initiated, the Bokeh server asks the Application for a new Document to service the session. To do this, the Application first creates a new empty Document, then it passes this Document to the modify_document method of each of its handlers. When all handlers have updated the Document, it is used to service the user session.

Subclasses must implement this method

Args:

doc (Document) : A Bokeh Document to update in-place

Returns:

Document

on_server_loaded(server_context: ServerContext) None[source]#

Execute code when the server is first started.

Subclasses may implement this method to provide for any one-time initialization that is necessary after the server starts, but before any sessions are created.

Args:

server_context (ServerContext) :

on_server_unloaded(server_context: ServerContext) None[source]#

Execute code when the server cleanly exits. (Before stopping the server’s IOLoop.)

Subclasses may implement this method to provide for any one-time tear down that is necessary before the server exits.

Args:

server_context (ServerContext) :

Warning

In practice this code may not run, since servers are often killed by a signal.

async on_session_created(session_context: SessionContext) None[source]#

Execute code when a new session is created.

Subclasses may implement this method to provide for any per-session initialization that is necessary before modify_doc is called for the session.

Args:

session_context (SessionContext) :

async on_session_destroyed(session_context: SessionContext) None[source]#

Execute code when a session is destroyed.

Subclasses may implement this method to provide for any per-session tear-down that is necessary when sessions are destroyed.

Args:

session_context (SessionContext) :

process_request(request: HTTPServerRequest) dict[str, Any][source]#

Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.

Args:

request: HTTP request

Returns:

A dictionary of JSON serializable data to be included on the session context.

property safe_to_fork: bool#

Whether it is still safe for the Bokeh server to fork new workers.

False if the code has already been executed.

static_path() str | None[source]#

Return a path to app-specific static resources, if applicable.

url_path() str | None[source]#

The last path component for the basename of the configured filename.

class panel.io.handlers.PanelCodeRunner(source: str, path: str | PathLike[str], argv: list[str], package: ModuleType | None = None)[source]#

Bases: CodeRunner

property doc: str | None#

Contents of docstring, if code contains one.

property error: str | None#

If code execution fails, may contain a related error message.

property error_detail: str | None#

If code execution fails, may contain a traceback or other details.

property failed: bool#

True if code execution failed

new_module() ModuleType | None[source]#

Make a fresh module to run in.

Returns:

Module

property path: str | PathLike[str]#

The path that new modules will be configured with.

reset_run_errors() None[source]#

Clears any transient error conditions from a previous run.

Returns

None

run(module: ModuleType, post_check: Callable[[], None] | None = None) None[source]#

Execute the configured source code in a module and run any post checks.

See bokeh.application.handlers.code_runner for original implementation.

property source: str#

The configured source code that will be executed when run is called.

class panel.io.handlers.ScriptHandler(*, filename: str | PathLike[str], argv: list[str] = [], package: ModuleType | None = None)[source]#

Bases: PanelCodeHandler

Modify Bokeh documents by creating Dashboard from a Python script.

property error: str | None#

If the handler fails, may contain a related error message.

property error_detail: str | None#

If the handler fails, may contain a traceback or other details.

property failed: bool#

True if the handler failed to modify the doc

modify_document(doc: Document)[source]#

Modify an application document in a specified manner.

When a Bokeh server session is initiated, the Bokeh server asks the Application for a new Document to service the session. To do this, the Application first creates a new empty Document, then it passes this Document to the modify_document method of each of its handlers. When all handlers have updated the Document, it is used to service the user session.

Subclasses must implement this method

Args:

doc (Document) : A Bokeh Document to update in-place

Returns:

Document

on_server_loaded(server_context: ServerContext) None[source]#

Execute code when the server is first started.

Subclasses may implement this method to provide for any one-time initialization that is necessary after the server starts, but before any sessions are created.

Args:

server_context (ServerContext) :

on_server_unloaded(server_context: ServerContext) None[source]#

Execute code when the server cleanly exits. (Before stopping the server’s IOLoop.)

Subclasses may implement this method to provide for any one-time tear down that is necessary before the server exits.

Args:

server_context (ServerContext) :

Warning

In practice this code may not run, since servers are often killed by a signal.

async on_session_created(session_context: SessionContext) None[source]#

Execute code when a new session is created.

Subclasses may implement this method to provide for any per-session initialization that is necessary before modify_doc is called for the session.

Args:

session_context (SessionContext) :

async on_session_destroyed(session_context: SessionContext) None[source]#

Execute code when a session is destroyed.

Subclasses may implement this method to provide for any per-session tear-down that is necessary when sessions are destroyed.

Args:

session_context (SessionContext) :

process_request(request: HTTPServerRequest) dict[str, Any][source]#

Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.

Args:

request: HTTP request

Returns:

A dictionary of JSON serializable data to be included on the session context.

property safe_to_fork: bool#

Whether it is still safe for the Bokeh server to fork new workers.

False if the code has already been executed.

static_path() str | None[source]#

Return a path to app-specific static resources, if applicable.

url_path() str | None[source]#

The last path component for the basename of the configured filename.

panel.io.handlers.capture_code_cell(cell)[source]#

Parses a code cell and generates wrapper code to capture the return value of the cell and any other outputs published inside the cell.

panel.io.handlers.extract_code(filehandle: IO, supported_syntax: tuple[str, ...] = ('{pyodide}', 'python')) str[source]#

Extracts Panel application code from a Markdown file.

panel.io.handlers.parse_notebook(filename: str | PathLike | IO, preamble: list[str] | None = None)[source]#

Parses a notebook on disk and returns a script.

Arguments#

filename: str | os.PathLike

The notebook file to parse.

preamble: list[str]

Any lines of code to prepend to the parsed code output.

Returns#

nb: nbformat.NotebookNode

nbformat dictionary-like representation of the notebook

code: str

The parsed and converted script

cell_layouts: dict

Dictionary containing the layout and positioning of cells.


ipywidget Module#

class panel.io.ipywidget.MessageSentBuffers[source]#

Bases: TypedDict

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 the key is not found, return the default if given; otherwise, raise a KeyError.

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: 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[source]#
dispatch(receiver: Any) None[source]#

Dispatch handling of this event to a receiver.

This method will invoke receiver._document_patched if it exists.

static handle_event(doc: Document, event_rep: DocumentPatched, setter: Setter | None) None[source]#
to_serializable(serializer: Serializer) MessageSent[source]#

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

Sub-classes must implement this method.

Args:

serializer (Serializer):

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

Bases: Kernel

async abort_request(stream, ident, parent)[source]#

abort a specific msg by id

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

async apply_request(stream, ident, parent)[source]#

Handle an apply request.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

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

Get the config section for this class.

Parameters#

classeslist, optional

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

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

Get the help string for this class in ReST format.

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

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

Get the helptext string for a single trait.

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

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

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

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

Works like event_handlers, except for excluding traits from parents.

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

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

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

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

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

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

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

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

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

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

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

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

classmethod clear_instance() None[source]#

unset _instance for this class and singleton parents.

async clear_request(stream, idents, parent)[source]#

Clear our namespace.

async comm_info_request(stream, ident, parent)[source]#

Handle a comm info request.

async complete_request(stream, ident, parent)[source]#

Handle a completion request.

async connect_request(stream, ident, parent)[source]#

Handle a connect request.

property cross_validation_lock: Any#

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

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

debug_just_my_code#

Set to False if you want to debug python standard and dependent libraries.

async debug_request(stream, ident, parent)[source]#

Handle a debug request.

async dispatch_queue()[source]#

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

dispatch shell requests

do_apply(content, bufs, msg_id, reply_metadata)[source]#

DEPRECATED

do_clear()[source]#

DEPRECATED since 4.0.3

do_complete(code, cursor_pos)[source]#

Override in subclasses to find completions.

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

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

Override in subclasses to access history.

do_inspect(code, cursor_pos, detail_level=0, omit_sections=())[source]#

Override in subclasses to allow introspection.

do_is_complete(code)[source]#

Override in subclasses to find completions.

async do_one_iteration()[source]#

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

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

enter_eventloop()[source]#

enter eventloop

async execute_request(stream, ident, parent)[source]#

handle an execute_request

finish_metadata(parent, metadata, reply_content)[source]#

Finish populating metadata.

Run after completing an execution request.

get_parent(channel=None)[source]#

Get the parent request associated with a channel.

Added in version 6.

Parameters#

channelstr

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

Returns#

messagedict

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

get_process_metric_value(process, name, attribute=None)[source]#

Get the process metric value.

getpass(prompt='', stream=None)[source]#

Forward getpass to frontends

Raises#

StdinNotImplementedError if active frontend doesn’t support stdin.

has_trait(name: str) bool[source]#

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

async history_request(stream, ident, parent)[source]#

Handle a history request.

hold_trait_notifications() Any[source]#

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

Initialize metadata.

Run at the beginning of execution requests.

classmethod initialized() bool[source]#

Has an instance been created?

async inspect_request(stream, ident, parent)[source]#

Handle an inspect request.

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

Returns a global instance of this class.

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

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

Examples#

Create a singleton class using instance, and retrieve it:

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

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

>>> class Bar(SingletonConfigurable): pass
>>> class Bam(Bar): pass
>>> bam = Bam.instance()
>>> bam == Bar.instance()
True
async interrupt_request(stream, ident, parent)[source]#

Handle an interrupt request.

async is_complete_request(stream, ident, parent)[source]#

Handle an is_complete request.

async kernel_info_request(stream, ident, parent)[source]#

Handle a kernel info request.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

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

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

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

nameslist, str, All

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

typestr, All (default: ‘change’)

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

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

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

This is used to setup dynamic notifications of trait changes.

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

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

Parameters#

handlercallable, None

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

namelist, str, None

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

removebool

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

post_handler_hook()[source]#

Hook to execute after calling message handler

pre_handler_hook()[source]#

Hook to execute before calling message handler

async process_control(msg)[source]#

dispatch control requests

async process_one(wait=True)[source]#

Process one request

Returns None if no message was handled.

raw_input(prompt='')[source]#

Forward raw_input to frontends

Raises#

StdinNotImplementedError if active frontend doesn’t support stdin.

record_ports(ports)[source]#

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

schedule a message for dispatch

classmethod section_names() list[str][source]#

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

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

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: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

shell_streams: List[t.Any]#

Deprecated shell_streams alias. Use shell_stream

Changed in version 6.0: shell_streams is deprecated. Use shell_stream.

should_handle(stream, msg, idents)[source]#

Check whether a shell-channel message should be handled

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

async shutdown_request(stream, ident, parent)[source]#

Handle a shutdown request.

start()[source]#

register dispatchers for streams

stop_on_error_timeout#

time (in seconds) to wait for messages to arrive when aborting queued requests after an error.

Requests that arrive within this window after an error will be cancelled.

Increase in the event of unusually slow network causing significant delays, which can manifest as e.g. “Run all” in a notebook aborting some, but not all, messages after an error.

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

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

Notes#

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

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

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

Parameters#

namestr (default: None)

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

Returns#

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

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

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

Example

class MyClass(HasTraits):
    i = Int()


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

Get metadata values for trait by key.

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

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

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

A dict of trait names and their values.

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

Returns#

A dict of trait names and their values.

Notes#

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

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

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

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

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

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

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

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

typestr or All (default: ‘change’)

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

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

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

update_config(config: Config) None[source]#

Update config and load the new values

async usage_request(stream, ident, parent)[source]#

Handle a usage request.

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

Bases: SessionWebsocket

add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

buffer_threshold#

Threshold (in bytes) beyond which an object’s buffer should be extracted to avoid pickling.

check_pid#

Whether to check PID to protect against calls after fork.

This check can be disabled if fork-safety is handled elsewhere.

classmethod class_config_rst_doc() str[source]#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

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

Get the config section for this class.

Parameters#

classeslist, optional

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

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

Get the help string for this class in ReST format.

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

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

Get the helptext string for a single trait.

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

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

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

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

Works like event_handlers, except for excluding traits from parents.

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

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

Works like class_traits, except for excluding traits from parents.

classmethod class_print_help(inst: HasTraits | None = None) None[source]#

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

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

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

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

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

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

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.

Added in version 5.1.

copy_threshold#

Threshold (in bytes) beyond which a buffer should be sent without copying.

property cross_validation_lock: Any#

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

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

debug#

Debug output in the Session

deserialize(msg_list: List[bytes] | List[Frame], content: bool = True, copy: bool = True) Dict[str, Any][source]#

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_listlist of bytes or Message objects

The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,…].

contentbool (True)

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

copybool (True)

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

Returns#

msgdict

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

digest_history_size#

The maximum number of digests to remember.

The digest history will be culled when it exceeds this value.

feed_identities(msg_list: List[bytes] | List[Frame], copy: bool = True) Tuple[List[bytes], List[bytes] | List[Frame]][source]#

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_lista list of Message or bytes objects

The message to be split.

copybool

flag determining whether the arguments are bytes or Messages

Returns#

(idents, msg_list)two lists

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.

has_trait(name: str) bool[source]#

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

hold_trait_notifications() Any[source]#

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.

item_threshold#

The maximum number of items for a container to be introspected for custom serialization. Containers larger than this are pickled outright.

key#

execution key, for signing messages.

keyfile#

path to file containing execution key.

metadata#

Metadata dictionary, which serves as the default top-level metadata dict for each message.

msg(msg_type: str, content: Dict | None = None, parent: Dict[str, Any] | None = None, header: Dict[str, Any] | None = None, metadata: Dict[str, Any] | None = None) Dict[str, Any][source]#

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: Bunch) None[source]#

Notify observers of a change event

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

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters#

handlercallable

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

nameslist, str, All

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

typestr, All (default: ‘change’)

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

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

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

This is used to setup dynamic notifications of trait changes.

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

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

Parameters#

handlercallable, None

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

namelist, str, None

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

removebool

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

packer#

The name of the packer for serializing messages. Should be one of ‘json’, ‘pickle’, or an import name for a custom callable serializer.

recv(socket: ~zmq.sugar.socket.Socket, mode: int = <Flag.DONTWAIT: 1>, content: bool = True, copy: bool = True) Tuple[List[bytes] | None, Dict[str, Any] | None][source]#

Receive and unpack a message.

Parameters#

socketZMQStream or Socket

The socket or stream to use in receiving.

Returns#

[idents], msg

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

classmethod section_names() list[str][source]#

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#

streamzmq.Socket or ZMQStream

The socket-like object used to send the data.

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

contentdict or None

The content of the message (ignored if msg_or_type is a message).

headerdict or None

The header dict for the message (ignored if msg_to_type is a message).

parentMessage or dict or None

The parent or parent header describing the parent of this message (ignored if msg_or_type is a message).

identbytes or list of bytes

The zmq.IDENTITY routing path.

metadatadict or None

The metadata describing the message

bufferslist or None

The already-serialized buffers to be appended to the message.

trackbool

Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages.

Returns#

msgdict

The constructed message.

send_raw(stream: Socket, msg_list: List, flags: int = 0, copy: bool = True, ident: List[bytes] | bytes | None = None) None[source]#

Send a raw message via ident path.

This method is used to send a already serialized message.

Parameters#

streamZMQStream or Socket

The ZMQ stream or socket to use for sending the message.

msg_listlist

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.

identident or list

A single ident or a list of idents to use in sending.

serialize(msg: Dict[str, Any], ident: List[bytes] | bytes | None = None) List[bytes][source]#

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#

msgdict or Message

The next message dict as returned by the self.msg method.

Returns#

msg_listlist

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.

session#

The UUID identifying this session.

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

sign(msg_list: List) bytes[source]#

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

Parameters#

msg_listlist

The [p_header,p_parent,p_content] part of the message list.

signature_scheme#

The digest scheme used to construct the message signatures. Must have the form ‘hmac-HASH’.

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

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

Notes#

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

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

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

Parameters#

namestr (default: None)

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

Returns#

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

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

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

Example

class MyClass(HasTraits):
    i = Int()


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

Get metadata values for trait by key.

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

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

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

A dict of trait names and their values.

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

Returns#

A dict of trait names and their values.

Notes#

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

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

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

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

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

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

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters#

handlercallable

The callable called when a trait attribute changes.

nameslist, str, All (default: All)

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

typestr or All (default: ‘change’)

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

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

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

unpacker#

The name of the unpacker for unserializing messages. Only used with custom functions for packer.

update_config(config: Config) None[source]#

Update config and load the new values

username#

Username for the Session. Default is your system username.

class panel.io.ipywidget.TempComm(target_name: str = 'comm', data: Dict[str, Any] | None = None, metadata: Dict[str, Any] | None = None, buffers: List[bytes] | None = None, comm_id: str | None = None, primary: bool = True, target_module: str | None = None, topic: bytes | None = None, _open_data: Dict[str, Any] | None = None, _close_data: Dict[str, Any] | None = None, **kwargs: Any)[source]#

Bases: BaseComm

close(data: Dict[str, Any] | None = None, metadata: Dict[str, Any] | None = None, buffers: List[bytes] | None = None, deleting: bool = False) None[source]#

Close the frontend-side version of this comm

handle_close(msg: Dict[str, Any]) None[source]#

Handle a comm_close message

handle_msg(msg: Dict[str, Any]) None[source]#

Handle a comm_msg message

on_close(callback: Callable[[Dict[str, Any]], None] | None) None[source]#

Register a callback for comm_close

Will be called with the data of the close message.

Call on_close(None) to disable an existing callback.

on_msg(callback: Callable[[Dict[str, Any]], None] | None) None[source]#

Register a callback for comm_msg

Will be called with the data of any comm_msg messages.

Call on_msg(None) to disable an existing callback.

open(data: Dict[str, Any] | None = None, metadata: Dict[str, Any] | None = None, buffers: List[bytes] | None = None) None[source]#

Open the frontend-side version of this comm

send(data: Dict[str, Any] | None = None, metadata: Dict[str, Any] | None = None, buffers: List[bytes] | None = None) None[source]#

Send a message to the frontend-side version of this comm


jupyter_executor Module#

class panel.io.jupyter_executor.JupyterServerSession(session_id: ID, document: Document, io_loop: IOLoop | None = None, token: str | None = None)[source]#

Bases: ServerSession

notify_connection_lost() None[source]#

Notify the document that the connection was lost.

classmethod patch(message: msg.patch_doc, connection: ServerConnection) msg.ok[source]#

Handle a PATCH-DOC, return a Future with work to be scheduled.

classmethod pull(message: msg.pull_doc_req, connection: ServerConnection) msg.pull_doc_reply[source]#

Handle a PULL-DOC, return a Future with work to be scheduled.

classmethod push(message: msg.push_doc, connection: ServerConnection) msg.ok[source]#

Handle a PUSH-DOC, return a Future with work to be scheduled.

request_expiration() None[source]#

Used in test suite for now. Forces immediate expiration if no connections.

subscribe(connection: ServerConnection) None[source]#

This should only be called by ServerConnection.subscribe_session or our book-keeping will be broken

property token: str#

A JWT token to authenticate the session.

unsubscribe(connection: ServerConnection) None[source]#

This should only be called by ServerConnection.unsubscribe_session or our book-keeping will be broken

async with_document_locked(func: Callable[[...], T], *args: Any, **kwargs: Any) T[source]#

Asynchronously locks the document and runs the function with it locked.

class panel.io.jupyter_executor.PanelExecutor(path, token, root_url, resources='server')[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: bytes | str | int | Integral | datetime) None[source]#

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

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

Args:
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[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

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

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

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

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

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

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

Deletes the cookie with the given name.

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

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

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

clear_header(name: str) None[source]#

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: int | None = None, reason: str | None = None) None[source]#

Closes this Web Socket.

Once the close handshake is successful the socket will be closed.

code may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1. reason may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.

Changed in version 4.0: Added the code and reason arguments.

compute_etag() str | None[source]#

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

Signs and timestamps a string so it cannot be forged.

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

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

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

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

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

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

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

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

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

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

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

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

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

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

Take control of the underlying stream.

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

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

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

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

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

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

Returns a list of the arguments with the given name.

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

This method searches both the query and body arguments.

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

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

Override to return compression options for the connection.

If this method returns None (the default), compression will be disabled. If it returns a dict (even an empty one), it will be enabled. The contents of the dict may be used to control the following compression options:

compression_level specifies the compression level.

mem_level specifies the amount of memory used for the internal compression state.

These parameters are documented in details here: https://docs.python.org/3.6/library/zlib.html#zlib.compressobj

Added in version 4.1.

Changed in version 4.5: Added compression_level and mem_level.

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

If the named cookie is not present, returns default.

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

get_current_user()[source]#

Delegate to the synchronous get_user method of the auth provider

get_login_url()[source]#

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

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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

May be overridden by subclasses to add or modify values.

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

get_template_path() str | None[source]#

Override to customize template path for each handler.

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

get_user_locale() Locale | None[source]#

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)[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: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

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

Added in version 3.1.

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

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

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.

Args:

fragment (unicode or bytes) : wire fragment to process

on_ping(data: bytes) None[source]#

Invoked when the a ping frame is received.

on_pong(data: bytes) None[source]#

Invoked when the response to a ping frame is received.

open() None[source]#

Initialize a connection to a client.

Returns:

None

ping(data: str | bytes = b'') None[source]#

Send ping frame to the remote end.

The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications.

Consider using the websocket_ping_interval application setting instead of sending pings manually.

Changed in version 5.1: The data argument is now optional.

property ping_interval: float | None#

The interval for websocket keep-alive pings.

Set websocket_ping_interval = 0 to disable pings.

property ping_timeout: float | None#

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

async prepare()[source]#

Async counterpart to get_current_user

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

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

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

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

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

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

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

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

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

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

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

select_subprotocol(subprotocols: list[str]) str | None[source]#

Override to implement subprotocol negotiation.

subprotocols is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, or None to not select a subprotocol.

Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.

The list may be empty, in which case this method must return None. This method is always called exactly once even if no subprotocols were proposed so that the handler can be advised of this fact.

Changed in version 5.1: Previously, this method was called with a list containing an empty string instead of an empty list if no subprotocols were proposed by the client.

property selected_subprotocol: str | None#

The subprotocol returned by select_subprotocol.

Added in version 5.1.

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

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

Send a Bokeh Server protocol message to the connected client.

Args:

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.

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

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

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

set_default_headers() None[source]#

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

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

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

This method is called automatically when the request is finished.

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

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

Set the no-delay flag for this stream.

By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call self.set_nodelay(True) once the websocket connection is established.

See .BaseIOStream.set_nodelay for additional details.

Added in version 3.1.

Signs and timestamps a cookie so it cannot be forged.

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

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

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

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

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

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

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

Signs and timestamps a cookie so it cannot be forged.

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

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

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

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

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

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

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

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

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: bool | None = None, **kwargs: Any) str[source]#

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

Writes the given chunk to the output buffer.

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

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

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

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

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

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.


jupyter_server_extension Module#

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

Bases: JupyterHandler

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

Adds the given response header and value.

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

property allow_credentials: bool#

Whether to set Access-Control-Allow-Credentials

property allow_origin: str#

Normal Access-Control-Allow-Origin

property allow_origin_pat: str | None#

Regular expression version of allow_origin

check_etag_header() bool[source]#

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

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

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

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

check_host() bool[source]#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool[source]#

Check Origin for cross-site API requests, including websockets

Copied from WebSocket with changes:

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

  • allow token-authenticated requests

check_referer() bool[source]#

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

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

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

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

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

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

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

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

Deletes the cookie with the given name.

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

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

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

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

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

Clear a login cookie.

compute_etag() str | None[source]#

Computes the etag header to be used for this request.

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

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

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

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

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

Signs and timestamps a string so it cannot be forged.

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

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

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

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

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

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

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

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

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

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

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

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

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

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

Take control of the underlying stream.

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

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

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

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

Flushes the current output buffer to the network.

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

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

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

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

Returns a list of the arguments with the given name.

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

This method searches both the query and body arguments.

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

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

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

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

If the named cookie is not present, returns default.

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

get_current_user() str[source]#

Get the current user.

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

Return the body of the request as JSON data.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

get_status() int[source]#

Returns the status code for our response.

get_template(name)[source]#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any][source]#

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

May be overridden by subclasses to add or modify values.

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

get_template_path() str | None[source]#

Override to customize template path for each handler.

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

get_user_locale() Locale | None[source]#

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: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

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

property log: Logger#

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

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

Override to customize logging of uncaught exceptions.

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

Added in version 3.1.

property logged_in: bool#

Is a user currently logged in?

property login_available: bool#

May a user proceed to log in?

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

property login_handler: Any#

Return the login handler for this application, if any.

on_connection_close() None[source]#

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

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(*, _redirect_to_login=True) Awaitable[None] | None[source]#

Prepare a response.

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

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

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

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

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

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

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

Generate the given template with the given arguments.

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

render_template(name, **ns)[source]#

Render a template by name.

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

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

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

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

Sends the given HTTP error code to the browser.

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

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

set_attachment_header(filename: str) None[source]#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

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

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

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

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

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

set_cors_headers() None[source]#

Add CORS headers, if defined

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

set_default_headers() None[source]#

Add CORS headers, if defined

set_etag_header() None[source]#

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

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

This method is called automatically when the request is finished.

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

Sets the given response header name and value.

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

Signs and timestamps a cookie so it cannot be forged.

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

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

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

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

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

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

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

Signs and timestamps a cookie so it cannot be forged.

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

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

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

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

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

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

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

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

Sets the status code for our response.

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

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

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

property settings: Dict[str, Any]#

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

skip_check_origin() bool[source]#

Ask my login_handler if I should skip the origin_check

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

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

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

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

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

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

property token: str | None#

Return the login token for this application, if any.

property token_authenticated: bool#

Have I been authenticated with a token?

property version_hash: str#

The version hash to use for cache hints for static files

write(chunk: str | bytes | dict) None[source]#

Writes the given chunk to the output buffer.

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

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

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

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

render custom error pages

xsrf_form_html() str[source]#

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

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: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

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

property allow_credentials: bool#

Whether to set Access-Control-Allow-Credentials

property allow_origin: str#

Normal Access-Control-Allow-Origin

property allow_origin_pat: str | None#

Regular expression version of allow_origin

check_etag_header() bool[source]#

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

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

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

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

check_host() bool[source]#

Check the host header if remote access disallowed.

Returns True if the request should continue, False otherwise.

check_origin(origin_to_satisfy_tornado: str = '') bool[source]#

Check Origin for cross-site API requests, including websockets

Copied from WebSocket with changes:

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

  • allow token-authenticated requests

check_referer() bool[source]#

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

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

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

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

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

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

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

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

Deletes the cookie with the given name.

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

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

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

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

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

Clear a login cookie.

compute_etag() str | None[source]#

Computes the etag header to be used for this request.

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

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

property content_security_policy: str#

The default Content-Security-Policy header

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

property cookies: Dict[str, Morsel]#

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

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

Signs and timestamps a string so it cannot be forged.

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

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

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

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

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

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

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

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

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

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

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

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

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

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

Take control of the underlying stream.

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

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

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

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

Flushes the current output buffer to the network.

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

Changed in version 6.0: The callback argument was removed.

Force a cookie clear.

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

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

Returns a list of the arguments with the given name.

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

This method searches both the query and body arguments.

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

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

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

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

If the named cookie is not present, returns default.

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

get_current_user() str[source]#

Get the current user.

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

Return the body of the request as JSON data.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 3.2.

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

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

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

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

Changed in version 3.2.1:

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

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

Returns the signing key version of the secure cookie.

The version is returned as int.

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

get_status() int[source]#

Returns the status code for our response.

get_template(name)[source]#

Return the jinja template object for a given name

get_template_namespace() Dict[str, Any][source]#

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

May be overridden by subclasses to add or modify values.

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

get_template_path() str | None[source]#

Override to customize template path for each handler.

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

get_user_locale() Locale | None[source]#

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: dict[str, Any]#

User-supplied values to supply to jinja templates.

property locale: Locale#

The locale for the current session.

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

property log: Logger#

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

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

Override to customize logging of uncaught exceptions.

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

Added in version 3.1.

property logged_in: bool#

Is a user currently logged in?

property login_available: bool#

May a user proceed to log in?

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

property login_handler: Any#

Return the login handler for this application, if any.

on_connection_close() None[source]#

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

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(*, _redirect_to_login=True) Awaitable[None] | None[source]#

Prepare a response.

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

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

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

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

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

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

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

Generate the given template with the given arguments.

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

render_template(name, **ns)[source]#

Render a template by name.

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

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

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

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

Sends the given HTTP error code to the browser.

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

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

set_attachment_header(filename: str) None[source]#

Set Content-Disposition: attachment header

As a method to ensure handling of filename encoding

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

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

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

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

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

set_cors_headers() None[source]#

Add CORS headers, if defined

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

set_default_headers() None[source]#

Add CORS headers, if defined

set_etag_header() None[source]#

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

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

This method is called automatically when the request is finished.

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

Sets the given response header name and value.

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

Signs and timestamps a cookie so it cannot be forged.

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

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

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

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

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

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

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