panel.io Package#
io
Package#
The io module contains utilities for loading JS components, embedding model state, and rendering panel objects.
- class panel.io.PeriodicCallback(**params)[source]#
Bases:
Parameterized
Periodic encapsulates a periodic callback which will run both in tornado based notebook environments and on bokeh server. By default the callback will run until the stop method is called, but count and timeout values can be set to limit the number of executions or the maximum length of time for which the callback will run. The callback may also be started and stopped by setting the running parameter to True or False respectively.
callback
= param.Callable(allow_None=True, label=’Callback’)The callback to execute periodically.
counter
= param.Integer(default=0, inclusive_bounds=(True, True), label=’Counter’)Counts the number of executions.
count
= param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Count’)Number of times the callback will be executed, by default this is unlimited.
log
= param.Boolean(bounds=(0, 1), default=True, label=’Log’)Whether the periodic callback should log its actions.
period
= param.Integer(default=500, inclusive_bounds=(True, True), label=’Period’)Period in milliseconds at which the callback is executed.
timeout
= param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Timeout’)Timeout in milliseconds from the start time at which the callback expires.
running
= param.Boolean(bounds=(0, 1), default=False, label=’Running’)Toggles whether the periodic callback is currently running.
- class panel.io.Resources(*args, absolute=False, notebook=False, **kwargs)[source]#
Bases:
Resources
- panel.io.ipywidget(obj: Any, doc=None, **kwargs: Any)#
Returns an ipywidget model which renders the Panel object.
Requires jupyter_bokeh to be installed.
- Parameters:
obj (object) – Any Panel object or object which can be rendered with Panel
doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.
**kwargs (dict) – Keyword arguments passed to the pn.panel utility function
- Return type:
Returns an ipywidget model which renders the Panel object.
- panel.io.profile(name, engine='pyinstrument')[source]#
A decorator which may be added to any function to record profiling output.
- Parameters:
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) None [source]#
Pushes events stored on the document across the provided comm.
- panel.io.push_notebook(*objs: Viewable) None [source]#
A utility for pushing updates to the frontend given a Panel object. This is required when modifying any Bokeh object directly in a notebook session.
- Parameters:
objs (panel.viewable.Viewable) –
- panel.io.serve(panels: TViewableFuncOrPath | Mapping[str, TViewableFuncOrPath], port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str | list[str]] = None, loop: Optional[IOLoop] = None, show: bool = True, start: bool = True, title: Optional[str] = None, verbose: bool = True, location: bool = True, threaded: bool = False, admin: bool = False, **kwargs) threading.Thread | Server [source]#
Allows serving one or more panel objects on a single server. The panels argument should be either a Panel object or a function returning a Panel object or a dictionary of these two. If a dictionary is supplied the keys represent the slugs at which each app is served, e.g. serve({‘app’: panel1, ‘app2’: panel2}) will serve apps at /app and /app2 on the server.
Reference: https://panel.holoviz.org/user_guide/Server_Configuration.html#serving-multiple-apps
- Parameters:
panel (Viewable, function or {str: Viewable or function}) – A Panel object, a function returning a Panel object or a dictionary mapping from the URL slug to either.
port (int (optional, default=0)) – Allows specifying a specific port
address (str) – The address the server should listen on for HTTP requests.
websocket_origin (str or list(str) (optional)) –
A list of hosts that can connect to the websocket.
This is typically required when embedding a server app in an external web site.
If None, “localhost” is used.
loop (tornado.ioloop.IOLoop (optional, default=IOLoop.current())) – The tornado IOLoop to run the Server on
show (boolean (optional, default=True)) – Whether to open the server in a new browser tab on start
start (boolean(optional, default=True)) – Whether to start the Server
title (str or {str: str} (optional, default=None)) – An HTML title for the application or a dictionary mapping from the URL slug to a customized title
verbose (boolean (optional, default=True)) – Whether to print the address and port
location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.
threaded (boolean (default=False)) – Whether to start the server on a new Thread
admin (boolean (default=False)) – Whether to enable the admin panel
kwargs (dict) – Additional keyword arguments to pass to Server instance
- panel.io.unlocked() Iterator [source]#
Context manager which unlocks a Document and dispatches ModelChangedEvents triggered in the context body to all sockets on current sessions.
- panel.io.with_lock(func: Callable) Callable [source]#
Wrap a callback function to execute with a lock allowing the function to modify bokeh models directly.
- Parameters:
func (callable) – The callable to wrap
- Returns:
wrapper – Function wrapped to execute without a Document lock.
- Return type:
callable
admin
Module#

- class panel.io.admin.Data(*, fig, holomap, widgets, fps, max_frames, size, dpi, filename, info, css, widget_location)[source]#
Bases:
Parameterized
data
= param.List(bounds=(0, None), default=[], label=’Data’)
- class panel.io.admin.LogDataHandler(data)[source]#
Bases:
StreamHandler
- acquire()#
Acquire the I/O thread lock.
- addFilter(filter)#
Add the specified filter to this handler.
- close()#
Tidy up any resources used by the handler.
This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.
- createLock()#
Acquire a thread lock for serializing access to the underlying I/O.
- emit(record)[source]#
Emit a record.
If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.
- filter(record)#
Determine if a record is loggable by consulting all the filters.
The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.
Changed in version 3.2: Allow filters to be just callables.
- flush()#
Flushes the stream.
- format(record)#
Format the specified record.
If a formatter is set, use it. Otherwise, use the default formatter for the module.
- handle(record)#
Conditionally emit the specified logging record.
Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.
- handleError(record)#
Handle errors which occur during an emit() call.
This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.
- release()#
Release the I/O thread lock.
- removeFilter(filter)#
Remove the specified filter from this handler.
- setFormatter(fmt)#
Set the formatter for this handler.
- setLevel(level)#
Set the logging level of this handler. level must be an int or a str.
- setStream(stream)#
Sets the StreamHandler’s stream to the specified value, if it is different.
Returns the old stream, if the stream was changed, or None if it wasn’t.
browser
Module#

Defines a BrowserInfo component exposing the browser window and navigator APIs.
- class panel.io.browser.BrowserInfo(**params)[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, bounds=(0, 1), label=’Dark mode’)Whether the user prefers dark mode.
device_pixel_ratio
= param.Number(allow_None=True, inclusive_bounds=(True, True), label=’Device pixel ratio’)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, label=’Language’)The preferred language of the user, usually the language of the browser UI.
timezone
= param.String(allow_None=True, label=’Timezone’)The timezone configured as the local timezone of the user.
timezone_offset
= param.Number(allow_None=True, inclusive_bounds=(True, True), label=’Timezone offset’)The time offset from UTC in minutes.
webdriver
= param.Boolean(allow_None=True, bounds=(0, 1), label=’Webdriver’)Indicates whether the user agent is controlled by automation.
- get_root(doc: Document | None = None, comm: Comm | None = None, preprocess: bool = True) Model [source]#
Returns the root model and applies pre-processing hooks
- Parameters:
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
- Return type:
Returns the bokeh model corresponding to this panel object
cache
Module#
Implements memoization for functions with arbitrary arguments
- panel.io.cache.cache(func=None, hash_funcs=None, max_items=None, policy='LRU', ttl=None, to_disk=False, cache_path='./cache')[source]#
Decorator to memoize functions with options to configure the caching behavior
- Parameters:
func (callable) – The function to cache.
hash_funcs (dict or None) – A dictionary mapping from a type to a function which returns a hash for an object of that type. If provided this will override the default hashing function provided by Panel.
policy (str) –
- A caching policy when max_items is set, must be one of:
FIFO: First in - First out
LRU: Least recently used
LFU: Least frequently used
ttl (float or None) – The number of seconds to keep an item in the cache, or None if the cache should not expire. The default is None.
to_disk (bool) – Whether to cache to disk using diskcache.
cache_dir (str) – Directory to cache to on disk.
- panel.io.cache.compute_hash(func, hash_funcs, args, kwargs)[source]#
Computes a hash given a function and its arguments.
- Parameters:
func (callable) – The function to cache.
hash_funcs (dict) – A dictionary of custom hash functions indexed by type
args (tuple) – Arguments to hash
kwargs (dict) – Keyword arguments to hash
callbacks
Module#

Defines callbacks to be executed on a thread or by scheduling it on a running bokeh server.
- class panel.io.callbacks.PeriodicCallback(**params)[source]#
Bases:
Parameterized
Periodic encapsulates a periodic callback which will run both in tornado based notebook environments and on bokeh server. By default the callback will run until the stop method is called, but count and timeout values can be set to limit the number of executions or the maximum length of time for which the callback will run. The callback may also be started and stopped by setting the running parameter to True or False respectively.
callback
= param.Callable(allow_None=True, label=’Callback’)The callback to execute periodically.
counter
= param.Integer(default=0, inclusive_bounds=(True, True), label=’Counter’)Counts the number of executions.
count
= param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Count’)Number of times the callback will be executed, by default this is unlimited.
log
= param.Boolean(bounds=(0, 1), default=True, label=’Log’)Whether the periodic callback should log its actions.
period
= param.Integer(default=500, inclusive_bounds=(True, True), label=’Period’)Period in milliseconds at which the callback is executed.
timeout
= param.Integer(allow_None=True, inclusive_bounds=(True, True), label=’Timeout’)Timeout in milliseconds from the start time at which the callback expires.
running
= param.Boolean(bounds=(0, 1), default=False, label=’Running’)Toggles whether the periodic callback is currently running.
convert
Module#

- class panel.io.convert.MockSessionContext(*args, document=None, **kwargs)[source]#
Bases:
SessionContext
- property destroyed: bool#
If
True
, the session has been discarded and cannot be used.A new session with the same ID could be created later but this instance will not come back to life.
- property id: ID#
The unique ID for the session associated with this context.
- property server_context: ServerContext#
The server context for this session context
- with_locked_document(*args)[source]#
Runs a function with the document lock held, passing the document to the function.
Subclasses must implement this method.
- Parameters:
func (callable) – function that takes a single parameter (the Document) and returns
None
or aFuture
- Returns:
a
Future
containing the result of the function
- class panel.io.convert.Request(headers: 'dict', cookies: 'dict', arguments: 'dict')[source]#
Bases:
object
- panel.io.convert.convert_apps(apps: str | os.PathLike | List[str | os.PathLike], dest_path: str | os.PathLike | None = None, title: str | None = None, runtime: Runtimes = 'pyodide-worker', requirements: List[str] | Literal['auto'] | os.PathLike = 'auto', prerender: bool = True, build_index: bool = True, build_pwa: bool = True, pwa_config: Dict[Any, Any] = {}, max_workers: int = 4, panel_version: Literal['auto', 'local'] | str = 'auto', http_patch: bool = True, inline: 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.
- 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.
- panel.io.convert.script_to_html(filename: str | os.PathLike | IO, requirements: Literal['auto'] | List[str] = 'auto', js_resources: Literal['auto'] | List[str] = 'auto', css_resources: Literal['auto'] | List[str] | None = None, runtime: Runtimes = 'pyodide', prerender: bool = True, panel_version: Literal['auto', 'local'] | str = 'auto', manifest: str | None = None, http_patch: bool = True, inline: bool = False) str [source]#
Converts a Panel or Bokeh script to a standalone WASM Python application.
- Parameters:
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.
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.
datamodel
Module#

- class panel.io.datamodel.Parameterized(*, default: Init[T] = 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: Union[Type[Property[Any]], Property[Any]], converter: Callable[[Any], T]) Property[T] #
Declare that other types may be converted to this property type.
- Parameters:
tp (Property) – A type that may be converted automatically to this property type.
converter (callable) – A function accepting
value
to perform conversion of the value to this property type.
- Returns:
self
- asserts(fn: Callable[[HasProps, T], bool], msg_or_fn: str | Callable[[HasProps, str, T], None]) Property[T] #
Assert that prepared values satisfy given conditions.
Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a
ColumnDataSource
all collectively have the same length at all times.- Parameters:
fn (callable) – A function accepting
(obj, value)
that returns True if the value passes the assertion, or False otherwise.msg_or_fn (str or callable) – A message to print in case the assertion fails, or a function accepting
(obj, name, value)
to call in in case the assertion fails.
- Returns:
self
- is_valid(value: Any) bool #
Whether the value passes validation
- Parameters:
value (obj) – the value to validate against this property type
- Returns:
True if valid, False otherwise
- make_descriptors(name: str) list[bokeh.core.property.descriptors.PropertyDescriptor[T]] #
Return a list of
PropertyDescriptor
instances to install on a class, in order to delegate attribute access to this property.- Parameters:
name (str) – the name of the property these descriptors are for
- Returns:
list[PropertyDescriptor]
The descriptors returned are collected by the
MetaHasProps
metaclass and added toHasProps
subclasses during class creation.
- matches(new: T, old: T) bool #
Whether two parameters match values.
If either
new
orold
is a NumPy array or Pandas Series or Index, then the result ofnp.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 #
The default, transformed by prepare_value() and the theme overrides.
- transform(value: Any) T #
Change the value into the canonical format for this property.
- Parameters:
value (obj) – the value to apply transformation to.
- Returns:
transformed value
- Return type:
obj
- wrap(value: T) T #
Some property types need to wrap their values in special containers, etc.
- class panel.io.datamodel.ParameterizedList(*, default: Init[T] = Intrinsic, help: str | None = None)[source]#
Bases:
Property
Accept a list of Parameterized objects.
This property only exists to support type validation, e.g. for “accepts” clauses. It is not serializable itself, and is not useful to add to Bokeh models directly.
- accepts(tp: Union[Type[Property[Any]], Property[Any]], converter: Callable[[Any], T]) Property[T] #
Declare that other types may be converted to this property type.
- Parameters:
tp (Property) – A type that may be converted automatically to this property type.
converter (callable) – A function accepting
value
to perform conversion of the value to this property type.
- Returns:
self
- asserts(fn: Callable[[HasProps, T], bool], msg_or_fn: str | Callable[[HasProps, str, T], None]) Property[T] #
Assert that prepared values satisfy given conditions.
Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a
ColumnDataSource
all collectively have the same length at all times.- Parameters:
fn (callable) – A function accepting
(obj, value)
that returns True if the value passes the assertion, or False otherwise.msg_or_fn (str or callable) – A message to print in case the assertion fails, or a function accepting
(obj, name, value)
to call in in case the assertion fails.
- Returns:
self
- is_valid(value: Any) bool #
Whether the value passes validation
- Parameters:
value (obj) – the value to validate against this property type
- Returns:
True if valid, False otherwise
- make_descriptors(name: str) list[bokeh.core.property.descriptors.PropertyDescriptor[T]] #
Return a list of
PropertyDescriptor
instances to install on a class, in order to delegate attribute access to this property.- Parameters:
name (str) – the name of the property these descriptors are for
- Returns:
list[PropertyDescriptor]
The descriptors returned are collected by the
MetaHasProps
metaclass and added toHasProps
subclasses during class creation.
- matches(new: T, old: T) bool #
Whether two parameters match values.
If either
new
orold
is a NumPy array or Pandas Series or Index, then the result ofnp.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 #
The default, transformed by prepare_value() and the theme overrides.
- transform(value: Any) T #
Change the value into the canonical format for this property.
- Parameters:
value (obj) – the value to apply transformation to.
- Returns:
transformed value
- Return type:
obj
- validate(value, detail=True)[source]#
Determine whether we can set this property from this value.
Validation happens before transform()
- Parameters:
value (obj) – the value to validate against this property type
detail (bool, options) –
whether to construct detailed exceptions
Generating detailed type validation error messages can be expensive. When doing type checks internally that will not escape exceptions to users, these messages can be skipped by setting this value to False (default: True)
- Returns:
None
- Raises:
ValueError if the value is not valid for this property type –
- wrap(value: T) T #
Some property types need to wrap their values in special containers, etc.
- panel.io.datamodel.construct_data_model(parameterized, name=None, ignore=[], types={})[source]#
Dynamically creates a Bokeh DataModel class from a Parameterized object.
- Parameters:
parameterized (param.Parameterized) – The Parameterized class or instance from which to create the DataModel
name (str or None) – Name of the dynamically created DataModel class
ignore (list(str)) – List of parameters to ignore.
types (dict) – A dictionary mapping from parameter name to a Parameter type, making it possible to override the default parameter types.
- Return type:
DataModel
- panel.io.datamodel.create_linked_datamodel(obj, root=None)[source]#
Creates a Bokeh DataModel from a Parameterized class or instance which automatically links the parameters bi-directionally.
- Parameters:
obj (param.Parameterized) – The Parameterized class to create a linked DataModel for.
- Return type:
DataModel instance linked to the Parameterized object.
django
Module#
document
Module#

- class panel.io.document.MockSessionContext(*args, document=None, **kwargs)[source]#
Bases:
SessionContext
- property destroyed: bool#
If
True
, the session has been discarded and cannot be used.A new session with the same ID could be created later but this instance will not come back to life.
- property id: ID#
The unique ID for the session associated with this context.
- property server_context: ServerContext#
The server context for this session context
- with_locked_document(*args)[source]#
Runs a function with the document lock held, passing the document to the function.
Subclasses must implement this method.
- Parameters:
func (callable) – function that takes a single parameter (the Document) and returns
None
or aFuture
- Returns:
a
Future
containing the result of the function
- class panel.io.document.Request(headers: 'dict', cookies: 'dict', arguments: 'dict')[source]#
Bases:
object
- panel.io.document.unlocked() Iterator [source]#
Context manager which unlocks a Document and dispatches ModelChangedEvents triggered in the context body to all sockets on current sessions.
- panel.io.document.with_lock(func: Callable) Callable [source]#
Wrap a callback function to execute with a lock allowing the function to modify bokeh models directly.
- Parameters:
func (callable) – The callable to wrap
- Returns:
wrapper – Function wrapped to execute without a Document lock.
- Return type:
callable
embed
Module#
Various utilities for recording and embedding state in a rendered app.
- panel.io.embed.embed_state(panel, model, doc, max_states=1000, max_opts=3, json=False, json_prefix='', save_path='./', load_path=None, progress=True, states={})[source]#
Embeds the state of the application on a State model which allows exporting a static version of an app. This works by finding all widgets with a predefined set of options and evaluating the cross product of the widget values and recording the resulting events to be replayed when exported. The state is recorded on a State model which is attached as an additional root on the Document.
- Parameters:
panel (panel.reactive.Reactive) – The Reactive component being exported
model (bokeh.model.Model) – The bokeh model being exported
doc (bokeh.document.Document) – The bokeh Document being exported
max_states (int (default=1000)) – The maximum number of states to export
max_opts (int (default=3)) – The max number of ticks sampled in a continuous widget like a slider
json (boolean (default=True)) – Whether to export the data to json files
json_prefix (str (default='')) – Prefix for JSON filename
save_path (str (default='./')) – The path to save json files to
load_path (str (default=None)) – The path or URL the json files will be loaded from.
progress (boolean (default=True)) – Whether to report progress
states (dict (default={})) – A dictionary specifying the widget values to embed for each widget
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 key is not found, default is returned if given, otherwise KeyError is raised
- popitem()#
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)#
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. #
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values #
- class panel.io.ipywidget.MessageSentEventPatched(document: Document, msg_type: str, msg_data: Any | bytes, setter: Setter | None = None, callback_invoker: Invoker | None = None)[source]#
Bases:
MessageSentEvent
Patches MessageSentEvent with fix that ensures MessageSent event does not define msg_data (which is an assumption in BokehJS Document.apply_json_patch.)
- combine(event: DocumentChangedEvent) bool #
- dispatch(receiver: Any) None #
Dispatch handling of this event to a receiver.
This method will invoke
receiver._document_patched
if it exists.
- static handle_event(doc: Document, event_rep: DocumentPatched, setter: Setter | None) None #
- to_serializable(serializer: Serializer) MessageSent #
Create a JSON representation of this event suitable for sending to clients.
Sub-classes must implement this method.
- Parameters:
serializer (Serializer) –
- class panel.io.ipywidget.PanelKernel(**kwargs: Any)[source]#
Bases:
Kernel
- async abort_request(stream, ident, parent)#
abort a specific msg by id
- add_traits(**traits)#
Dynamically add trait attributes to the HasTraits instance.
- async apply_request(stream, ident, parent)#
Handle an apply request.
- classmethod class_config_rst_doc()#
Generate rST documentation for this class’ config options.
Excludes traits defined on parent classes.
- classmethod class_config_section(classes=None)#
Get the config section for this class.
- Parameters:
classes (list, optional) – The list of other classes in the config file. Used to reduce redundant information.
- classmethod class_get_help(inst=None)#
Get the help string for this class in ReST format.
If inst is given, its current trait values will be used in place of class defaults.
- classmethod class_get_trait_help(trait, inst=None, helptext=None)#
Get the helptext string for a single trait.
- Parameters:
inst – If given, its current trait values will be used in place of the class default.
helptext – If not given, uses the help attribute of the current trait.
- classmethod class_own_trait_events(name)#
Get a dict of all event handlers defined on this class, not a parent.
Works like
event_handlers
, except for excluding traits from parents.
- classmethod class_own_traits(**metadata)#
Get a dict of all the traitlets defined on this class, not a parent.
Works like class_traits, except for excluding traits from parents.
- classmethod class_print_help(inst=None)#
Get the help string for a single trait and print it.
- classmethod class_trait_names(**metadata)#
Get a list of all the names of this class’ traits.
This method is just like the
trait_names()
method, but is unbound.
- classmethod class_traits(**metadata)#
Get a
dict
of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.This method is just like the
traits()
method, but is unbound.The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- classmethod clear_instance()#
unset _instance for this class and singleton parents.
- async clear_request(stream, idents, parent)#
Clear our namespace.
- async comm_info_request(stream, ident, parent)#
Handle a comm info request.
- async complete_request(stream, ident, parent)#
Handle a completion request.
- async connect_request(stream, ident, parent)#
Handle a connect request.
- property cross_validation_lock#
A contextmanager for running a block with our cross validation lock set to True.
At the end of the block, the lock’s value is restored to its value prior to entering the block.
- debug_just_my_code#
Set to False if you want to debug python standard and dependent libraries.
- async debug_request(stream, ident, parent)#
Handle a debug request.
- async dispatch_queue()#
Coroutine to preserve order of message handling
Ensures that only one message is processing at a time, even when the handler is async
- async dispatch_shell(msg)#
dispatch shell requests
- do_apply(content, bufs, msg_id, reply_metadata)#
DEPRECATED
- do_clear()#
DEPRECATED since 4.0.3
- do_complete(code, cursor_pos)#
Override in subclasses to find completions.
- do_execute(code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_id=None)#
Execute user code. Must be overridden by subclasses.
- do_history(hist_access_type, output, raw, session=None, start=None, stop=None, n=None, pattern=None, unique=False)#
Override in subclasses to access history.
- do_inspect(code, cursor_pos, detail_level=0, omit_sections=())#
Override in subclasses to allow introspection.
- do_is_complete(code)#
Override in subclasses to find completions.
- async do_one_iteration()#
Process a single shell message
Any pending control messages will be flushed as well
Changed in version 5: This is now a coroutine
- do_shutdown(restart)#
Override in subclasses to do things when the frontend shuts down the kernel.
- enter_eventloop()#
enter eventloop
- async execute_request(stream, ident, parent)#
handle an execute_request
- finish_metadata(parent, metadata, reply_content)#
Finish populating metadata.
Run after completing an execution request.
- get_parent(channel='shell')#
Get the parent request associated with a channel.
New in version 6.
- Parameters:
channel (str) – the name of the channel (‘shell’ or ‘control’)
- Returns:
message – the parent message for the most recent request on the channel.
- Return type:
dict
- get_process_metric_value(process, name, attribute=None)#
Get the process metric value.
- getpass(prompt='', stream=None)#
Forward getpass to frontends
- Raises:
StdinNotImplementedError if active frontend doesn't support stdin. –
- has_trait(name)#
Returns True if the object has a trait with the specified name.
- async history_request(stream, ident, parent)#
Handle a history request.
- hold_trait_notifications()#
Context manager for bundling trait change notifications and cross validation.
Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.
- init_metadata(parent)#
Initialize metadata.
Run at the beginning of execution requests.
- classmethod initialized()#
Has an instance been created?
- async inspect_request(stream, ident, parent)#
Handle an inspect request.
- classmethod instance(*args, **kwargs)#
Returns a global instance of this class.
This method create a new instance if none have previously been created and returns a previously created instance is one already exists.
The arguments and keyword arguments passed to this method are passed on to the
__init__()
method of the class upon instantiation.Examples
Create a singleton class using instance, and retrieve it:
>>> from traitlets.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True
Create a subclass that is retrived using the base class instance:
>>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True
- async interrupt_request(stream, ident, parent)#
Handle an interrupt request.
- async is_complete_request(stream, ident, parent)#
Handle an is_complete request.
- async kernel_info_request(stream, ident, parent)#
Handle a kernel info request.
- notify_change(change)#
Notify observers of a change event
- observe(handler, names=traitlets.All, type='change')#
Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
- Parameters:
handler (callable) – A callable that is called when a trait changes. Its signature should be
handler(change)
, wherechange
is a dictionary. The change dictionary at least holds a ‘type’ key. *type
: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: *owner
: the HasTraits instance *old
: the old value of the modified trait attribute *new
: the new value of the modified trait attribute *name
: the name of the modified trait attribute.names (list, str, All) – If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.
type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.
- on_trait_change(handler=None, name=None, remove=False)#
DEPRECATED: Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).
If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.
- Parameters:
handler (callable, None) – A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).
name (list, str, None) – If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.
remove (bool) – If False (the default), then install the handler. If True then unintall it.
- post_handler_hook()#
Hook to execute after calling message handler
- pre_handler_hook()#
Hook to execute before calling message handler
- async process_control(msg)#
dispatch control requests
- async process_one(wait=True)#
Process one request
Returns None if no message was handled.
- raw_input(prompt='')#
Forward raw_input to frontends
- Raises:
StdinNotImplementedError if active frontend doesn't support stdin. –
- record_ports(ports)#
Record the ports that this kernel is using.
The creator of the Kernel instance must call this methods if they want the
connect_request()
method to return the port numbers.
- schedule_dispatch(dispatch, *args)#
schedule a message for dispatch
- classmethod section_names()#
return section names as a list
- send_response(stream, msg_or_type, content=None, ident=None, buffers=None, track=False, header=None, metadata=None, channel='shell')#
Send a response to the message we’re currently processing.
This accepts all the parameters of
jupyter_client.session.Session.send()
exceptparent
.This relies on
set_parent()
having been called for the current message.
- set_parent(ident, parent, channel='shell')#
Set the current parent request
Side effects (IOPub messages) and replies are associated with the request that caused them via the parent_header.
The parent identity is used to route input_request messages on the stdin channel.
- set_trait(name, value)#
Forcibly sets trait attribute, including read-only attributes.
- setup_instance(**kwargs)#
This is called before self.__init__ is called.
- shell_streams#
Deprecated shell_streams alias. Use shell_stream
Changed in version 6.0: shell_streams is deprecated. Use shell_stream.
- should_handle(stream, msg, idents)#
Check whether a shell-channel message should be handled
Allows subclasses to prevent handling of certain messages (e.g. aborted requests).
- async shutdown_request(stream, ident, parent)#
Handle a shutdown request.
- start()#
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, **metadata)#
Return a trait’s default value or a dictionary of them
Notes
Dynamically generated default values may depend on the current state of the object.
- classmethod trait_events(name=None)#
Get a
dict
of all the event handlers of this class.- Parameters:
name (str (default: None)) – The name of a trait of this class. If name is
None
then all the event handlers of this class will be returned instead.- Return type:
The event handlers associated with a trait name, or all event handlers.
- trait_has_value(name)#
Returns True if the specified trait has a value.
This will return false even if
getattr
would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.Example
class MyClass(HasTraits): i = Int() mc = MyClass() assert not mc.trait_has_value("i") mc.i # generates a default value assert mc.trait_has_value("i")
- trait_metadata(traitname, key, default=None)#
Get metadata values for trait by key.
- trait_names(**metadata)#
Get a list of all the names of this class’ traits.
- trait_values(**metadata)#
A
dict
of trait names and their values.The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- Return type:
A
dict
of trait names and their values.
Notes
Trait values are retrieved via
getattr
, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the resultdict
.
- traits(**metadata)#
Get a
dict
of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- unobserve(handler, names=traitlets.All, type='change')#
Remove a trait change handler.
This is used to unregister handlers to trait change notifications.
- Parameters:
handler (callable) – The callable called when a trait attribute changes.
names (list, str, All (default: All)) – The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.
type (str or All (default: 'change')) – The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.
- unobserve_all(name=traitlets.All)#
Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.
- update_config(config)#
Update config and load the new values
- async usage_request(stream, ident, parent)#
Handle a usage request.
- class panel.io.ipywidget.PanelSessionWebsocket(**kwargs: Any)[source]#
Bases:
SessionWebsocket
- add_traits(**traits)#
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()#
Generate rST documentation for this class’ config options.
Excludes traits defined on parent classes.
- classmethod class_config_section(classes=None)#
Get the config section for this class.
- Parameters:
classes (list, optional) – The list of other classes in the config file. Used to reduce redundant information.
- classmethod class_get_help(inst=None)#
Get the help string for this class in ReST format.
If inst is given, its current trait values will be used in place of class defaults.
- classmethod class_get_trait_help(trait, inst=None, helptext=None)#
Get the helptext string for a single trait.
- Parameters:
inst – If given, its current trait values will be used in place of the class default.
helptext – If not given, uses the help attribute of the current trait.
- classmethod class_own_trait_events(name)#
Get a dict of all event handlers defined on this class, not a parent.
Works like
event_handlers
, except for excluding traits from parents.
- classmethod class_own_traits(**metadata)#
Get a dict of all the traitlets defined on this class, not a parent.
Works like class_traits, except for excluding traits from parents.
- classmethod class_print_help(inst=None)#
Get the help string for a single trait and print it.
- classmethod class_trait_names(**metadata)#
Get a list of all the names of this class’ traits.
This method is just like the
trait_names()
method, but is unbound.
- classmethod class_traits(**metadata)#
Get a
dict
of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.This method is just like the
traits()
method, but is unbound.The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- clone() Session #
Create a copy of this Session
Useful when connecting multiple times to a given kernel. This prevents a shared digest_history warning about duplicate digests due to multiple connections to IOPub in the same process.
New in version 5.1.
- copy_threshold#
Threshold (in bytes) beyond which a buffer should be sent without copying.
- property cross_validation_lock#
A contextmanager for running a block with our cross validation lock set to True.
At the end of the block, the lock’s value is restored to its value prior to entering the block.
- debug#
Debug output in the Session
- deserialize(msg_list: Union[List[bytes], List[Frame]], content: bool = True, copy: bool = True) Dict[str, Any] #
Unserialize a msg_list to a nested message dict.
This is roughly the inverse of serialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.
- Parameters:
msg_list (list of bytes or Message objects) – The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,…].
content (bool (True)) – Whether to unpack the content dict (True), or leave it packed (False).
copy (bool (True)) – Whether msg_list contains bytes (True) or the non-copying Message objects in each place (False).
- Returns:
msg – The nested message dict with top-level keys [header, parent_header, content, buffers]. The buffers are returned as memoryviews.
- Return type:
dict
- 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: Union[List[bytes], List[Frame]], copy: bool = True) Tuple[List[bytes], Union[List[bytes], List[Frame]]] #
Split the identities from the rest of the message.
Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly.
- Parameters:
msg_list (a list of Message or bytes objects) – The message to be split.
copy (bool) – flag determining whether the arguments are bytes or Messages
- Returns:
(idents, msg_list) – idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,…] and should be unpackable/unserializable via self.deserialize at this point.
- Return type:
two lists
- has_trait(name)#
Returns True if the object has a trait with the specified name.
- hold_trait_notifications()#
Context manager for bundling trait change notifications and cross validation.
Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.
- 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: Optional[Dict] = None, parent: Optional[Dict[str, Any]] = None, header: Optional[Dict[str, Any]] = None, metadata: Optional[Dict[str, Any]] = None) Dict[str, Any] #
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.
- msg_header(msg_type: str) Dict[str, Any] #
Create a header for a message type.
- notify_change(change)#
Notify observers of a change event
- observe(handler, names=traitlets.All, type='change')#
Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
- Parameters:
handler (callable) – A callable that is called when a trait changes. Its signature should be
handler(change)
, wherechange
is a dictionary. The change dictionary at least holds a ‘type’ key. *type
: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: *owner
: the HasTraits instance *old
: the old value of the modified trait attribute *new
: the new value of the modified trait attribute *name
: the name of the modified trait attribute.names (list, str, All) – If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.
type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.
- on_trait_change(handler=None, name=None, remove=False)#
DEPRECATED: Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).
If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.
- Parameters:
handler (callable, None) – A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).
name (list, str, None) – If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.
remove (bool) – If False (the default), then install the handler. If True then unintall it.
- 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: Socket, mode: int = Flag.DONTWAIT, content: bool = True, copy: bool = True) Tuple[Optional[List[bytes]], Optional[Dict[str, Any]]] #
Receive and unpack a message.
- Parameters:
socket (ZMQStream or Socket) – The socket or stream to use in receiving.
- Returns:
[idents] is a list of idents and msg is a nested message dict of same format as self.msg returns.
- Return type:
[idents], msg
- classmethod section_names()#
return section names as a list
- send(stream, msg_type, content=None, parent=None, ident=None, buffers=None, track=False, header=None, metadata=None)[source]#
Build and send a message via stream or socket.
The message format used by this function internally is as follows:
- [ident1,ident2,…,DELIM,HMAC,p_header,p_parent,p_content,
buffer1,buffer2,…]
The serialize/deserialize methods convert the nested message dict into this format.
- Parameters:
stream (zmq.Socket or ZMQStream) – The socket-like object used to send the data.
msg_or_type (str or Message/dict) – Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header.
content (dict or None) – The content of the message (ignored if msg_or_type is a message).
header (dict or None) – The header dict for the message (ignored if msg_to_type is a message).
parent (Message or dict or None) – The parent or parent header describing the parent of this message (ignored if msg_or_type is a message).
ident (bytes or list of bytes) – The zmq.IDENTITY routing path.
metadata (dict or None) – The metadata describing the message
buffers (list or None) – The already-serialized buffers to be appended to the message.
track (bool) – Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages.
- Returns:
msg – The constructed message.
- Return type:
dict
- send_raw(stream: Socket, msg_list: List, flags: int = 0, copy: bool = True, ident: Optional[Union[List[bytes], bytes]] = None) None #
Send a raw message via ident path.
This method is used to send a already serialized message.
- Parameters:
stream (ZMQStream or Socket) – The ZMQ stream or socket to use for sending the message.
msg_list (list) – The serialized list of messages to send. This only includes the [p_header,p_parent,p_metadata,p_content,buffer1,buffer2,…] portion of the message.
ident (ident or list) – A single ident or a list of idents to use in sending.
- serialize(msg: Dict[str, Any], ident: Optional[Union[List[bytes], bytes]] = None) List[bytes] #
Serialize the message components to bytes.
This is roughly the inverse of deserialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list.
- Parameters:
msg (dict or Message) – The next message dict as returned by the self.msg method.
- Returns:
msg_list –
The list of bytes objects to be sent with the format:
[ident1, ident2, ..., DELIM, HMAC, p_header, p_parent, p_metadata, p_content, buffer1, buffer2, ...]
In this list, the
p_*
entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings.- Return type:
list
- session#
The UUID identifying this session.
- set_trait(name, value)#
Forcibly sets trait attribute, including read-only attributes.
- setup_instance(**kwargs)#
This is called before self.__init__ is called.
- sign(msg_list: List) bytes #
Sign a message with HMAC digest. If no auth, return b’’.
- Parameters:
msg_list (list) – The [p_header,p_parent,p_content] part of the message list.
- signature_scheme#
The digest scheme used to construct the message signatures. Must have the form ‘hmac-HASH’.
- trait_defaults(*names, **metadata)#
Return a trait’s default value or a dictionary of them
Notes
Dynamically generated default values may depend on the current state of the object.
- classmethod trait_events(name=None)#
Get a
dict
of all the event handlers of this class.- Parameters:
name (str (default: None)) – The name of a trait of this class. If name is
None
then all the event handlers of this class will be returned instead.- Return type:
The event handlers associated with a trait name, or all event handlers.
- trait_has_value(name)#
Returns True if the specified trait has a value.
This will return false even if
getattr
would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.Example
class MyClass(HasTraits): i = Int() mc = MyClass() assert not mc.trait_has_value("i") mc.i # generates a default value assert mc.trait_has_value("i")
- trait_metadata(traitname, key, default=None)#
Get metadata values for trait by key.
- trait_names(**metadata)#
Get a list of all the names of this class’ traits.
- trait_values(**metadata)#
A
dict
of trait names and their values.The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- Return type:
A
dict
of trait names and their values.
Notes
Trait values are retrieved via
getattr
, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the resultdict
.
- traits(**metadata)#
Get a
dict
of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.
The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.
- unobserve(handler, names=traitlets.All, type='change')#
Remove a trait change handler.
This is used to unregister handlers to trait change notifications.
- Parameters:
handler (callable) – The callable called when a trait attribute changes.
names (list, str, All (default: All)) – The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.
type (str or All (default: 'change')) – The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.
- unobserve_all(name=traitlets.All)#
Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.
- unpacker#
The name of the unpacker for unserializing messages. Only used with custom functions for packer.
- unserialize(*args: Any, **kwargs: Any) Dict[str, Any] #
DEPRECATED Use deserialize instead.
- update_config(config)#
Update config and load the new values
- username#
Username for the Session. Default is your system username.
- class panel.io.ipywidget.TempComm(target_name='comm', data=None, metadata=None, buffers=None, comm_id=None, primary=True, target_module=None, topic=None, _open_data=None, _close_data=None, **kwargs)[source]#
Bases:
BaseComm
- close(data=None, metadata=None, buffers=None, deleting=False)#
Close the frontend-side version of this comm
- handle_close(msg)#
Handle a comm_close message
- handle_msg(msg)#
Handle a comm_msg message
- on_close(callback)#
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)#
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=None, metadata=None, buffers=None)#
Open the frontend-side version of this comm
- send(data=None, metadata=None, buffers=None)#
Send a message to the frontend-side version of this comm
jupyter_executor
Module#

- class panel.io.jupyter_executor.PanelExecutor(path, token, root_url)[source]#
Bases:
WSHandler
The PanelExecutor is intended to be run inside a kernel where it runs a Panel application renders the HTML and then establishes a Jupyter Comm channel to communicate with the PanelWSProxy in order to send and receive messages to and from the frontend.
- add_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Adds the given response header and value.
Unlike set_header, add_header may be called multiple times to return multiple values for the same header.
- check_etag_header() bool #
Checks the
Etag
header against requests’sIf-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. TheEtag
header should be set (perhaps with set_etag_header) before calling this method.
- check_origin(origin: str) bool #
Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server allowlist. If the origin is not allow, an error will be logged and
False
will be returned.- Parameters:
origin (str) – The URL of the connection origin
- Returns:
bool, True if the connection is allowed, False otherwise
- check_xsrf_cookie() None #
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 allPOST
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 namedX-XSRFToken
orX-CSRFToken
(the latter is accepted for compatibility with Django).See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.
- clear() None #
Resets all headers and content for this response.
- clear_all_cookies(**kwargs: Any) None #
Attempt to delete all the cookies the user sent with this request.
See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the
domain
,path
,samesite
, orsecure
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
anddomain
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 useclear_cookie
one at a time instead.
- clear_cookie(name: str, **kwargs: Any) None #
Deletes the cookie with the given name.
This method accepts the same arguments as set_cookie, except for
expires
andmax_age
. Clearing a cookie requires the samedomain
andpath
arguments as when it was set. In some cases thesamesite
andsecure
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. Thesamesite
andsecure
flags have recently become required for clearingsamesite="none"
cookies.
- clear_header(name: str) None #
Clears an outgoing header, undoing a previous set_header call.
Note that this method does not apply to multi-valued headers set by add_header.
- close(code: Optional[int] = None, reason: Optional[str] = None) None #
Closes this Web Socket.
Once the close handshake is successful the socket will be closed.
code
may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1.reason
may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.Changed in version 4.0: Added the
code
andreason
arguments.
- compute_etag() Optional[str] #
Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.
- property cookies: Dict[str, Morsel]#
An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.
- create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes #
Signs and timestamps a string so it cannot be forged.
Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.
Changed in version 3.2.1: Added the
version
argument. Introduced cookie version 2 and made it the default.
- create_template_loader(template_path: str) BaseLoader #
Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a directory-based loader on the given path, using the
autoescape
andtemplate_whitespace
application settings. If atemplate_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) Optional[Awaitable[None]] #
Implement this method to handle streamed request data.
Requires the .stream_request_body decorator.
May be a coroutine for flow control.
- decode_argument(value: bytes, name: Optional[str] = None) str #
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.
The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
- detach() IOStream #
Take control of the underlying stream.
Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.
This method is only supported when HTTP/1.1 is used.
New in version 5.1.
- finish(chunk: Optional[Union[str, bytes, dict]] = None) Future[None] #
Finishes this response, ending the HTTP request.
Passing a
chunk
tofinish()
is equivalent to passing that chunk towrite()
and then callingfinish()
with no arguments.Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.
Changed in version 5.1: Now returns a .Future instead of
None
.
- flush(include_footers: bool = False) Future[None] #
Flushes the current output buffer to the network.
Changed in version 4.0: Now returns a .Future if no callback is given.
Changed in version 6.0: The
callback
argument was removed.
- get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the request more than once, we return the last value.
This method searches both the query and body arguments.
- get_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
- get_body_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request body.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_body_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_browser_locale(default: str = 'en_US') Locale #
Determines the user’s locale from
Accept-Language
header.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- get_compression_options() dict[str, Any] | None #
Override to return compression options for the connection.
If this method returns None (the default), compression will be disabled. If it returns a dict (even an empty one), it will be enabled. The contents of the dict may be used to control the following compression options:
compression_level
specifies the compression level.mem_level
specifies the amount of memory used for the internal compression state.These parameters are documented in details here: https://docs.python.org/3.6/library/zlib.html#zlib.compressobj
New in version 4.1.
Changed in version 4.5: Added
compression_level
andmem_level
.
- get_cookie(name: str, default: Optional[str] = None) Optional[str] #
Returns the value of the request cookie with the given name.
If the named cookie is not present, returns
default
.This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.
- get_current_user()#
Delegate to the synchronous
get_user
method of the auth provider
- get_login_url()#
Delegates to``get_login_url`` method of the auth provider, or the
login_url
attribute.
- get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request query string.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_query_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_secure_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_secure_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_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_signed_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_signed_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_signed_cookie_key_version
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_status() int #
Returns the status code for our response.
- get_template_namespace() Dict[str, Any] #
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.
- get_template_path() Optional[str] #
Override to customize template path for each handler.
By default, we use the
template_path
application setting. Return None to load templates relative to the calling file.
- get_user_locale() Optional[Locale] #
Override to determine the locale from the authenticated user.
If None is returned, we fall back to get_browser_locale().
This method should return a tornado.locale.Locale object, most likely obtained via a call like
tornado.locale.get("en")
- initialize(application_context, bokeh_websocket_path)#
- property locale: Locale#
The locale for the current session.
Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the
Accept-Language
header.
- log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) None #
Override to customize logging of uncaught exceptions.
By default logs instances of HTTPError as warnings without stack traces (on the
tornado.general
logger), and all other exceptions as errors with stack traces (on thetornado.application
logger).New in version 3.1.
- property max_message_size: int#
Maximum allowed message size.
If the remote peer sends a message larger than this, the connection will be closed.
Default is 10MiB.
- on_close() None #
Clean up when the connection is closed.
- on_connection_close() None #
Called in async handlers if the client closed the connection.
Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.
Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
- on_finish() None #
Called after the end of a request.
Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare.
on_finish
may not produce any output, as it is called after the response has been sent to the client.
- async on_message(fragment: str | bytes) None #
Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got.
- Parameters:
fragment (unicode or bytes) – wire fragment to process
- on_ping(data: bytes) None #
Invoked when the a ping frame is received.
- on_pong(data: bytes) None #
Invoked when the response to a ping frame is received.
- open() None #
Initialize a connection to a client.
- Returns:
None
- ping(data: Union[str, bytes] = b'') None #
Send ping frame to the remote end.
The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications.
Consider using the
websocket_ping_interval
application setting instead of sending pings manually.Changed in version 5.1: The data argument is now optional.
- property ping_interval: Optional[float]#
The interval for websocket keep-alive pings.
Set websocket_ping_interval = 0 to disable pings.
- property ping_timeout: Optional[float]#
If no ping is received in this many seconds, close the websocket connection (VPNs, etc. can fail to cleanly close ws connections). Default is max of 3 pings or 30 seconds.
- async prepare()#
Async counterpart to
get_current_user
- redirect(url: str, permanent: bool = False, status: Optional[int] = None) None #
Sends a redirect to the given (optionally relative) URL.
If the
status
argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on thepermanent
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 #
Default method used to render the final embedded css for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_embed_js(js_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded js for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_css(css_files: Iterable[str]) str #
Default method used to render the final css links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_js(js_files: Iterable[str]) str #
Default method used to render the final js links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_string(template_name: str, **kwargs: Any) bytes #
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
- require_setting(name: str, feature: str = 'this feature') None #
Raises an exception if the given app setting is not defined.
- reverse_url(name: str, *args: Any) str #
Alias for Application.reverse_url.
- select_subprotocol(subprotocols: list[str]) str | None #
Override to implement subprotocol negotiation.
subprotocols
is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, orNone
to not select a subprotocol.Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.
The list may be empty, in which case this method must return None. This method is always called exactly once even if no subprotocols were proposed so that the handler can be advised of this fact.
Changed in version 5.1: Previously, this method was called with a list containing an empty string instead of an empty list if no subprotocols were proposed by the client.
- property selected_subprotocol: Optional[str]#
The subprotocol returned by select_subprotocol.
New in version 5.1.
- send_error(status_code: int = 500, **kwargs: Any) None #
Sends the given HTTP error code to the browser.
If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.
Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.
- async send_message(message: Message[Any]) None #
Send a Bokeh Server protocol message to the connected client.
- Parameters:
message (Message) – a message to send
- set_cookie(name: str, value: Union[str, bytes], domain: Optional[str] = None, expires: Optional[Union[float, Tuple, datetime]] = None, path: str = '/', expires_days: Optional[float] = None, *, max_age: Optional[int] = None, httponly: bool = False, secure: bool = False, samesite: Optional[str] = None, **kwargs: Any) None #
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 #
Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom
Server
header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.
- set_etag_header() None #
Sets the response’s Etag header using
self.compute_etag()
.Note: no header will be set if
compute_etag()
returnsNone
.This method is called automatically when the request is finished.
- set_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Sets the given response header name and value.
All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the
Date
header).
- set_nodelay(value: bool) None #
Set the no-delay flag for this stream.
By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call
self.set_nodelay(True)
once the websocket connection is established.See .BaseIOStream.set_nodelay for additional details.
New in version 3.1.
- set_secure_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- set_signed_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_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: Optional[str] = None) None #
Sets the status code for our response.
- Parameters:
status_code (int) – Response status code.
reason (str) – Human-readable reason phrase describing the status code. If
None
, it will be filled in from http.client.responses or “Unknown”.
Changed in version 5.0: No longer validates that the response code is in http.client.responses.
- property settings: Dict[str, Any]#
An alias for self.application.settings <Application.settings>.
- static_url(path: str, include_host: Optional[bool] = None, **kwargs: Any) str #
Returns a static URL for the given relative static file path.
This method requires you set the
static_path
setting in your application (which specifies the root directory of your static files).This method returns a versioned url (by default appending
?v=<signature>
), which allows the static files to be cached indefinitely. This can be disabled by passinginclude_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 aninclude_host
attribute, that value will be used as the default for all static_url calls that do not passinclude_host
as a keyword argument.
- write(chunk: Union[str, bytes, dict]) None #
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be
application/json
. (if you want to send JSON as a differentContent-Type
, callset_header
after callingwrite()
).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 #
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 askwargs["exc_info"]
. Note that this exception may not be the “current” exception for purposes of methods likesys.exc_info()
ortraceback.format_exc
.
- async write_message(message: Union[bytes, str, Dict[str, Any]], binary: bool = False, locked: bool = True) None [source]#
Override parent write_message with a version that acquires a write lock before writing.
- xsrf_form_html() str #
An HTML
<input/>
element to be included with all POST forms.It defines the
_xsrf
input value, which we check on all POST requests to prevent cross-site request forgery. If you have set thexsrf_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 thesecure
andhttponly
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.PanelJupyterHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#
Bases:
JupyterHandler
The PanelJupyterHandler expects to be given a path to a notebook, .py file or Lumen .yaml file. Based on the kernelspec in the notebook or the kernel query parameter it will then provision a Jupyter kernel to run the Panel application in.
Once the kernel is launched it will instantiate a PanelExecutor inside the kernel and serve the HTML returned by it. If successful it will store the kernel and comm_id on panel.state.
- add_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Adds the given response header and value.
Unlike set_header, add_header may be called multiple times to return multiple values for the same header.
- property allow_credentials#
Whether to set Access-Control-Allow-Credentials
- property allow_origin#
Normal Access-Control-Allow-Origin
- property allow_origin_pat#
Regular expression version of allow_origin
- check_etag_header() bool #
Checks the
Etag
header against requests’sIf-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. TheEtag
header should be set (perhaps with set_etag_header) before calling this method.
- check_host()#
Check the host header if remote access disallowed.
Returns True if the request should continue, False otherwise.
- check_origin(origin_to_satisfy_tornado='')#
Check Origin for cross-site API requests, including websockets
Copied from WebSocket with changes:
allow unspecified host/origin (e.g. scripts)
allow token-authenticated requests
- check_referer()#
Check Referer for cross-site requests. Disables requests to certain endpoints with external or missing Referer. If set, allow_origin settings are applied to the Referer to whitelist specific cross-origin sites. Used on GET for api endpoints and /files/ to block cross-site inclusion (XSSI).
- check_xsrf_cookie()#
Bypass xsrf cookie checks when token-authenticated
- clear() None #
Resets all headers and content for this response.
- clear_all_cookies(**kwargs: Any) None #
Attempt to delete all the cookies the user sent with this request.
See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the
domain
,path
,samesite
, orsecure
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
anddomain
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 useclear_cookie
one at a time instead.
- clear_cookie(name: str, **kwargs: Any) None #
Deletes the cookie with the given name.
This method accepts the same arguments as set_cookie, except for
expires
andmax_age
. Clearing a cookie requires the samedomain
andpath
arguments as when it was set. In some cases thesamesite
andsecure
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. Thesamesite
andsecure
flags have recently become required for clearingsamesite="none"
cookies.
- clear_header(name: str) None #
Clears an outgoing header, undoing a previous set_header call.
Note that this method does not apply to multi-valued headers set by add_header.
- clear_login_cookie()#
Clear a login cookie.
- compute_etag() Optional[str] #
Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.
- property content_security_policy#
The default Content-Security-Policy header
Can be overridden by defining Content-Security-Policy in settings[‘headers’]
- property cookies: Dict[str, Morsel]#
An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.
- create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes #
Signs and timestamps a string so it cannot be forged.
Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.
Changed in version 3.2.1: Added the
version
argument. Introduced cookie version 2 and made it the default.
- create_template_loader(template_path: str) BaseLoader #
Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a directory-based loader on the given path, using the
autoescape
andtemplate_whitespace
application settings. If atemplate_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) Optional[Awaitable[None]] #
Implement this method to handle streamed request data.
Requires the .stream_request_body decorator.
May be a coroutine for flow control.
- decode_argument(value: bytes, name: Optional[str] = None) str #
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.
The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
- detach() IOStream #
Take control of the underlying stream.
Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.
This method is only supported when HTTP/1.1 is used.
New in version 5.1.
- finish(chunk: Optional[Union[str, bytes, dict]] = None) Future[None] #
Finishes this response, ending the HTTP request.
Passing a
chunk
tofinish()
is equivalent to passing that chunk towrite()
and then callingfinish()
with no arguments.Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.
Changed in version 5.1: Now returns a .Future instead of
None
.
- flush(include_footers: bool = False) Future[None] #
Flushes the current output buffer to the network.
Changed in version 4.0: Now returns a .Future if no callback is given.
Changed in version 6.0: The
callback
argument was removed.
- force_clear_cookie(name, path='/', domain=None)#
Force a cookie clear.
- get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the request more than once, we return the last value.
This method searches both the query and body arguments.
- get_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
- get_body_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request body.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_body_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_browser_locale(default: str = 'en_US') Locale #
Determines the user’s locale from
Accept-Language
header.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- get_cookie(name: str, default: Optional[str] = None) Optional[str] #
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()#
Get the current user.
- get_json_body()#
Return the body of the request as JSON data.
- get_login_url() str #
Override to customize the login URL based on the request.
By default, we use the
login_url
application setting.
- get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request query string.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_query_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_secure_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_secure_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_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_signed_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_signed_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_signed_cookie_key_version
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_status() int #
Returns the status code for our response.
- get_template(name)#
Return the jinja template object for a given name
- get_template_namespace() Dict[str, Any] #
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.
- get_template_path() Optional[str] #
Override to customize template path for each handler.
By default, we use the
template_path
application setting. Return None to load templates relative to the calling file.
- get_user_locale() Optional[Locale] #
Override to determine the locale from the authenticated user.
If None is returned, we fall back to get_browser_locale().
This method should return a tornado.locale.Locale object, most likely obtained via a call like
tornado.locale.get("en")
- property jinja_template_vars#
User-supplied values to supply to jinja templates.
- property locale: Locale#
The locale for the current session.
Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the
Accept-Language
header.
- property log#
use the Jupyter log by default, falling back on tornado’s logger
- log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) None #
Override to customize logging of uncaught exceptions.
By default logs instances of HTTPError as warnings without stack traces (on the
tornado.general
logger), and all other exceptions as errors with stack traces (on thetornado.application
logger).New in version 3.1.
- property logged_in#
Is a user currently logged in?
- property login_available#
May a user proceed to log in?
This returns True if login capability is available, irrespective of whether the user is already logged in or not.
- property login_handler#
Return the login handler for this application, if any.
- on_connection_close() None #
Called in async handlers if the client closed the connection.
Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.
Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
- on_finish() None #
Called after the end of a request.
Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare.
on_finish
may not produce any output, as it is called after the response has been sent to the client.
- async prepare()#
Pepare a response.
- redirect(url: str, permanent: bool = False, status: Optional[int] = None) None #
Sends a redirect to the given (optionally relative) URL.
If the
status
argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on thepermanent
argument. The default is 302 (temporary).
- render(template_name: str, **kwargs: Any) Future[None] #
Renders the template with the given arguments as the response.
render()
callsfinish()
, so no other output methods can be called after it.Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.
Changed in version 5.1: Now returns a .Future instead of
None
.
- render_embed_css(css_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded css for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_embed_js(js_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded js for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_css(css_files: Iterable[str]) str #
Default method used to render the final css links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_js(js_files: Iterable[str]) str #
Default method used to render the final js links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_string(template_name: str, **kwargs: Any) bytes #
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
- render_template(name, **ns)#
Render a template by name.
- require_setting(name: str, feature: str = 'this feature') None #
Raises an exception if the given app setting is not defined.
- reverse_url(name: str, *args: Any) str #
Alias for Application.reverse_url.
- send_error(status_code: int = 500, **kwargs: Any) None #
Sends the given HTTP error code to the browser.
If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.
Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.
- set_attachment_header(filename)#
Set Content-Disposition: attachment header
As a method to ensure handling of filename encoding
- set_cookie(name: str, value: Union[str, bytes], domain: Optional[str] = None, expires: Optional[Union[float, Tuple, datetime]] = None, path: str = '/', expires_days: Optional[float] = None, *, max_age: Optional[int] = None, httponly: bool = False, secure: bool = False, samesite: Optional[str] = None, **kwargs: Any) None #
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()#
Add CORS headers, if defined
Now that current_user is async (jupyter-server 2.0), must be called at the end of prepare(), instead of in set_default_headers.
- set_default_headers()#
Add CORS headers, if defined
- set_etag_header() None #
Sets the response’s Etag header using
self.compute_etag()
.Note: no header will be set if
compute_etag()
returnsNone
.This method is called automatically when the request is finished.
- set_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Sets the given response header name and value.
All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the
Date
header).
- set_secure_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- set_signed_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_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: Optional[str] = None) None #
Sets the status code for our response.
- Parameters:
status_code (int) – Response status code.
reason (str) – Human-readable reason phrase describing the status code. If
None
, it will be filled in from http.client.responses or “Unknown”.
Changed in version 5.0: No longer validates that the response code is in http.client.responses.
- property settings: Dict[str, Any]#
An alias for self.application.settings <Application.settings>.
- skip_check_origin()#
Ask my login_handler if I should skip the origin_check
For example: in the default LoginHandler, if a request is token-authenticated, origin checking should be skipped.
- static_url(path: str, include_host: Optional[bool] = None, **kwargs: Any) str #
Returns a static URL for the given relative static file path.
This method requires you set the
static_path
setting in your application (which specifies the root directory of your static files).This method returns a versioned url (by default appending
?v=<signature>
), which allows the static files to be cached indefinitely. This can be disabled by passinginclude_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 aninclude_host
attribute, that value will be used as the default for all static_url calls that do not passinclude_host
as a keyword argument.
- property token#
Return the login token for this application, if any.
- property token_authenticated#
Have I been authenticated with a token?
- property version_hash#
The version hash to use for cache hints for static files
- write(chunk: Union[str, bytes, dict]) None #
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be
application/json
. (if you want to send JSON as a differentContent-Type
, callset_header
after callingwrite()
).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, **kwargs)#
render custom error pages
- xsrf_form_html() str #
An HTML
<input/>
element to be included with all POST forms.It defines the
_xsrf
input value, which we check on all POST requests to prevent cross-site request forgery. If you have set thexsrf_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 thesecure
andhttponly
flags on the_xsrf
cookie.
- class panel.io.jupyter_server_extension.PanelWSProxy(tornado_app, *args, **kw)[source]#
Bases:
WSHandler
,JupyterHandler
The PanelWSProxy serves as a proxy between the frontend and the Jupyter kernel that is running the Panel application. It send and receives Bokeh protocol messages via a Jupyter Comm.
- add_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Adds the given response header and value.
Unlike set_header, add_header may be called multiple times to return multiple values for the same header.
- property allow_credentials#
Whether to set Access-Control-Allow-Credentials
- property allow_origin#
Normal Access-Control-Allow-Origin
- property allow_origin_pat#
Regular expression version of allow_origin
- check_etag_header() bool #
Checks the
Etag
header against requests’sIf-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. TheEtag
header should be set (perhaps with set_etag_header) before calling this method.
- check_host()#
Check the host header if remote access disallowed.
Returns True if the request should continue, False otherwise.
- check_origin(origin: str) bool [source]#
Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server allowlist. If the origin is not allow, an error will be logged and
False
will be returned.- Parameters:
origin (str) – The URL of the connection origin
- Returns:
bool, True if the connection is allowed, False otherwise
- check_referer()#
Check Referer for cross-site requests. Disables requests to certain endpoints with external or missing Referer. If set, allow_origin settings are applied to the Referer to whitelist specific cross-origin sites. Used on GET for api endpoints and /files/ to block cross-site inclusion (XSSI).
- check_xsrf_cookie()#
Bypass xsrf cookie checks when token-authenticated
- clear() None #
Resets all headers and content for this response.
- clear_all_cookies(**kwargs: Any) None #
Attempt to delete all the cookies the user sent with this request.
See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the
domain
,path
,samesite
, orsecure
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
anddomain
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 useclear_cookie
one at a time instead.
- clear_cookie(name: str, **kwargs: Any) None #
Deletes the cookie with the given name.
This method accepts the same arguments as set_cookie, except for
expires
andmax_age
. Clearing a cookie requires the samedomain
andpath
arguments as when it was set. In some cases thesamesite
andsecure
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. Thesamesite
andsecure
flags have recently become required for clearingsamesite="none"
cookies.
- clear_header(name: str) None #
Clears an outgoing header, undoing a previous set_header call.
Note that this method does not apply to multi-valued headers set by add_header.
- clear_login_cookie()#
Clear a login cookie.
- close(code: Optional[int] = None, reason: Optional[str] = None) None #
Closes this Web Socket.
Once the close handshake is successful the socket will be closed.
code
may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1.reason
may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.Changed in version 4.0: Added the
code
andreason
arguments.
- compute_etag() Optional[str] #
Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.
- property content_security_policy#
The default Content-Security-Policy header
Can be overridden by defining Content-Security-Policy in settings[‘headers’]
- property cookies: Dict[str, Morsel]#
An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.
- create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes #
Signs and timestamps a string so it cannot be forged.
Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.
Changed in version 3.2.1: Added the
version
argument. Introduced cookie version 2 and made it the default.
- create_template_loader(template_path: str) BaseLoader #
Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a directory-based loader on the given path, using the
autoescape
andtemplate_whitespace
application settings. If atemplate_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) Optional[Awaitable[None]] #
Implement this method to handle streamed request data.
Requires the .stream_request_body decorator.
May be a coroutine for flow control.
- decode_argument(value: bytes, name: Optional[str] = None) str #
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.
The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
- detach() IOStream #
Take control of the underlying stream.
Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.
This method is only supported when HTTP/1.1 is used.
New in version 5.1.
- finish(chunk: Optional[Union[str, bytes, dict]] = None) Future[None] #
Finishes this response, ending the HTTP request.
Passing a
chunk
tofinish()
is equivalent to passing that chunk towrite()
and then callingfinish()
with no arguments.Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.
Changed in version 5.1: Now returns a .Future instead of
None
.
- flush(include_footers: bool = False) Future[None] #
Flushes the current output buffer to the network.
Changed in version 4.0: Now returns a .Future if no callback is given.
Changed in version 6.0: The
callback
argument was removed.
- force_clear_cookie(name, path='/', domain=None)#
Force a cookie clear.
- get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the request more than once, we return the last value.
This method searches both the query and body arguments.
- get_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
- get_body_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request body.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_body_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_browser_locale(default: str = 'en_US') Locale #
Determines the user’s locale from
Accept-Language
header.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- get_compression_options() dict[str, Any] | None #
Override to return compression options for the connection.
If this method returns None (the default), compression will be disabled. If it returns a dict (even an empty one), it will be enabled. The contents of the dict may be used to control the following compression options:
compression_level
specifies the compression level.mem_level
specifies the amount of memory used for the internal compression state.These parameters are documented in details here: https://docs.python.org/3.6/library/zlib.html#zlib.compressobj
New in version 4.1.
Changed in version 4.5: Added
compression_level
andmem_level
.
- get_cookie(name: str, default: Optional[str] = None) Optional[str] #
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_json_body()#
Return the body of the request as JSON data.
- get_login_url()#
Delegates to``get_login_url`` method of the auth provider, or the
login_url
attribute.
- get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request query string.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_query_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_secure_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_secure_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_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_signed_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_signed_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_signed_cookie_key_version
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_status() int #
Returns the status code for our response.
- get_template(name)#
Return the jinja template object for a given name
- get_template_namespace() Dict[str, Any] #
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.
- get_template_path() Optional[str] #
Override to customize template path for each handler.
By default, we use the
template_path
application setting. Return None to load templates relative to the calling file.
- get_user_locale() Optional[Locale] #
Override to determine the locale from the authenticated user.
If None is returned, we fall back to get_browser_locale().
This method should return a tornado.locale.Locale object, most likely obtained via a call like
tornado.locale.get("en")
- property jinja_template_vars#
User-supplied values to supply to jinja templates.
- property locale: Locale#
The locale for the current session.
Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the
Accept-Language
header.
- property log#
use the Jupyter log by default, falling back on tornado’s logger
- log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) None #
Override to customize logging of uncaught exceptions.
By default logs instances of HTTPError as warnings without stack traces (on the
tornado.general
logger), and all other exceptions as errors with stack traces (on thetornado.application
logger).New in version 3.1.
- property logged_in#
Is a user currently logged in?
- property login_available#
May a user proceed to log in?
This returns True if login capability is available, irrespective of whether the user is already logged in or not.
- property login_handler#
Return the login handler for this application, if any.
- property max_message_size: int#
Maximum allowed message size.
If the remote peer sends a message larger than this, the connection will be closed.
Default is 10MiB.
- on_connection_close() None #
Called in async handlers if the client closed the connection.
Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.
Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
- on_finish() None #
Called after the end of a request.
Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare.
on_finish
may not produce any output, as it is called after the response has been sent to the client.
- async on_message(fragment: str | bytes) None [source]#
Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got.
- Parameters:
fragment (unicode or bytes) – wire fragment to process
- on_ping(data: bytes) None #
Invoked when the a ping frame is received.
- on_pong(data: bytes) None #
Invoked when the response to a ping frame is received.
- ping(data: Union[str, bytes] = b'') None #
Send ping frame to the remote end.
The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications.
Consider using the
websocket_ping_interval
application setting instead of sending pings manually.Changed in version 5.1: The data argument is now optional.
- property ping_interval: Optional[float]#
The interval for websocket keep-alive pings.
Set websocket_ping_interval = 0 to disable pings.
- property ping_timeout: Optional[float]#
If no ping is received in this many seconds, close the websocket connection (VPNs, etc. can fail to cleanly close ws connections). Default is max of 3 pings or 30 seconds.
- redirect(url: str, permanent: bool = False, status: Optional[int] = None) None #
Sends a redirect to the given (optionally relative) URL.
If the
status
argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on thepermanent
argument. The default is 302 (temporary).
- render(template_name: str, **kwargs: Any) Future[None] #
Renders the template with the given arguments as the response.
render()
callsfinish()
, so no other output methods can be called after it.Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.
Changed in version 5.1: Now returns a .Future instead of
None
.
- render_embed_css(css_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded css for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_embed_js(js_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded js for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_css(css_files: Iterable[str]) str #
Default method used to render the final css links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_js(js_files: Iterable[str]) str #
Default method used to render the final js links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_string(template_name: str, **kwargs: Any) bytes #
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
- render_template(name, **ns)#
Render a template by name.
- require_setting(name: str, feature: str = 'this feature') None #
Raises an exception if the given app setting is not defined.
- reverse_url(name: str, *args: Any) str #
Alias for Application.reverse_url.
- select_subprotocol(subprotocols: list[str]) str | None #
Override to implement subprotocol negotiation.
subprotocols
is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, orNone
to not select a subprotocol.Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.
The list may be empty, in which case this method must return None. This method is always called exactly once even if no subprotocols were proposed so that the handler can be advised of this fact.
Changed in version 5.1: Previously, this method was called with a list containing an empty string instead of an empty list if no subprotocols were proposed by the client.
- property selected_subprotocol: Optional[str]#
The subprotocol returned by select_subprotocol.
New in version 5.1.
- send_error(status_code: int = 500, **kwargs: Any) None #
Sends the given HTTP error code to the browser.
If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.
Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.
- async send_message(message: Message[Any]) None #
Send a Bokeh Server protocol message to the connected client.
- Parameters:
message (Message) – a message to send
- set_attachment_header(filename)#
Set Content-Disposition: attachment header
As a method to ensure handling of filename encoding
- set_cookie(name: str, value: Union[str, bytes], domain: Optional[str] = None, expires: Optional[Union[float, Tuple, datetime]] = None, path: str = '/', expires_days: Optional[float] = None, *, max_age: Optional[int] = None, httponly: bool = False, secure: bool = False, samesite: Optional[str] = None, **kwargs: Any) None #
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()#
Add CORS headers, if defined
Now that current_user is async (jupyter-server 2.0), must be called at the end of prepare(), instead of in set_default_headers.
- set_default_headers()#
Add CORS headers, if defined
- set_etag_header() None #
Sets the response’s Etag header using
self.compute_etag()
.Note: no header will be set if
compute_etag()
returnsNone
.This method is called automatically when the request is finished.
- set_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Sets the given response header name and value.
All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the
Date
header).
- set_nodelay(value: bool) None #
Set the no-delay flag for this stream.
By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call
self.set_nodelay(True)
once the websocket connection is established.See .BaseIOStream.set_nodelay for additional details.
New in version 3.1.
- set_secure_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- set_signed_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_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: Optional[str] = None) None #
Sets the status code for our response.
- Parameters:
status_code (int) – Response status code.
reason (str) – Human-readable reason phrase describing the status code. If
None
, it will be filled in from http.client.responses or “Unknown”.
Changed in version 5.0: No longer validates that the response code is in http.client.responses.
- property settings: Dict[str, Any]#
An alias for self.application.settings <Application.settings>.
- skip_check_origin()#
Ask my login_handler if I should skip the origin_check
For example: in the default LoginHandler, if a request is token-authenticated, origin checking should be skipped.
- static_url(path: str, include_host: Optional[bool] = None, **kwargs: Any) str #
Returns a static URL for the given relative static file path.
This method requires you set the
static_path
setting in your application (which specifies the root directory of your static files).This method returns a versioned url (by default appending
?v=<signature>
), which allows the static files to be cached indefinitely. This can be disabled by passinginclude_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 aninclude_host
attribute, that value will be used as the default for all static_url calls that do not passinclude_host
as a keyword argument.
- property token#
Return the login token for this application, if any.
- property token_authenticated#
Have I been authenticated with a token?
- property version_hash#
The version hash to use for cache hints for static files
- write(chunk: Union[str, bytes, dict]) None #
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be
application/json
. (if you want to send JSON as a differentContent-Type
, callset_header
after callingwrite()
).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, **kwargs)#
render custom error pages
- async write_message(message: bytes | str | dict[str, Any], binary: bool = False, locked: bool = True) None #
Override parent write_message with a version that acquires a write lock before writing.
- xsrf_form_html() str #
An HTML
<input/>
element to be included with all POST forms.It defines the
_xsrf
input value, which we check on all POST requests to prevent cross-site request forgery. If you have set thexsrf_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 thesecure
andhttponly
flags on the_xsrf
cookie.
- async panel.io.jupyter_server_extension.ensure_async(obj: Awaitable | Any) Any [source]#
Convert a non-awaitable object to a coroutine if needed, and await it if it was not already awaited.
- panel.io.jupyter_server_extension.generate_executor(path: str, token: str, root_url: str) str [source]#
Generates the code to instantiate a PanelExecutor that is to be be run on the kernel to start a server session.
- Parameters:
path (str) – The path of the Panel application to execute.
token (str) – The Bokeh JWT token containing the session_id, request arguments, headers and cookies.
root_url (str) – The root_url the server is running on.
- Return type:
The code to be executed inside the kernel.
liveness
Module#

- class panel.io.liveness.LivenessHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#
Bases:
RequestHandler
- add_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Adds the given response header and value.
Unlike set_header, add_header may be called multiple times to return multiple values for the same header.
- check_etag_header() bool #
Checks the
Etag
header against requests’sIf-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. TheEtag
header should be set (perhaps with set_etag_header) before calling this method.
- check_xsrf_cookie() None #
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 allPOST
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 namedX-XSRFToken
orX-CSRFToken
(the latter is accepted for compatibility with Django).See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.
- clear() None #
Resets all headers and content for this response.
- clear_all_cookies(**kwargs: Any) None #
Attempt to delete all the cookies the user sent with this request.
See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the
domain
,path
,samesite
, orsecure
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
anddomain
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 useclear_cookie
one at a time instead.
- clear_cookie(name: str, **kwargs: Any) None #
Deletes the cookie with the given name.
This method accepts the same arguments as set_cookie, except for
expires
andmax_age
. Clearing a cookie requires the samedomain
andpath
arguments as when it was set. In some cases thesamesite
andsecure
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. Thesamesite
andsecure
flags have recently become required for clearingsamesite="none"
cookies.
- clear_header(name: str) None #
Clears an outgoing header, undoing a previous set_header call.
Note that this method does not apply to multi-valued headers set by add_header.
- compute_etag() Optional[str] #
Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.
- property cookies: Dict[str, Morsel]#
An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.
- create_signed_value(name: str, value: Union[str, bytes], version: Optional[int] = None) bytes #
Signs and timestamps a string so it cannot be forged.
Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.
Changed in version 3.2.1: Added the
version
argument. Introduced cookie version 2 and made it the default.
- create_template_loader(template_path: str) BaseLoader #
Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a directory-based loader on the given path, using the
autoescape
andtemplate_whitespace
application settings. If atemplate_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) Optional[Awaitable[None]] #
Implement this method to handle streamed request data.
Requires the .stream_request_body decorator.
May be a coroutine for flow control.
- decode_argument(value: bytes, name: Optional[str] = None) str #
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.
The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
- detach() IOStream #
Take control of the underlying stream.
Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.
This method is only supported when HTTP/1.1 is used.
New in version 5.1.
- finish(chunk: Optional[Union[str, bytes, dict]] = None) Future[None] #
Finishes this response, ending the HTTP request.
Passing a
chunk
tofinish()
is equivalent to passing that chunk towrite()
and then callingfinish()
with no arguments.Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.
Changed in version 5.1: Now returns a .Future instead of
None
.
- flush(include_footers: bool = False) Future[None] #
Flushes the current output buffer to the network.
Changed in version 4.0: Now returns a .Future if no callback is given.
Changed in version 6.0: The
callback
argument was removed.
- get_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the request more than once, we return the last value.
This method searches both the query and body arguments.
- get_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
- get_body_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request body.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_body_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_browser_locale(default: str = 'en_US') Locale #
Determines the user’s locale from
Accept-Language
header.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- get_cookie(name: str, default: Optional[str] = None) Optional[str] #
Returns the value of the request cookie with the given name.
If the named cookie is not present, returns
default
.This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.
- get_current_user() Any #
Override to determine the current user from, e.g., a cookie.
This method may not be a coroutine.
- get_login_url() str #
Override to customize the login URL based on the request.
By default, we use the
login_url
application setting.
- get_query_argument(name: str, default: ~typing.Union[None, str, ~tornado.web._ArgDefaultMarker] = <tornado.web._ArgDefaultMarker object>, strip: bool = True) Optional[str] #
Returns the value of the argument with the given name from the request query string.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
New in version 3.2.
- get_query_arguments(name: str, strip: bool = True) List[str] #
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
New in version 3.2.
- get_secure_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_secure_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_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_signed_cookie(name: str, value: Optional[str] = None, max_age_days: float = 31, min_version: Optional[int] = None) Optional[bytes] #
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
toget_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_signed_cookie_key_version(name: str, value: Optional[str] = None) Optional[int] #
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
toset_signed_cookie_key_version
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- get_status() int #
Returns the status code for our response.
- get_template_namespace() Dict[str, Any] #
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.
- get_template_path() Optional[str] #
Override to customize template path for each handler.
By default, we use the
template_path
application setting. Return None to load templates relative to the calling file.
- get_user_locale() Optional[Locale] #
Override to determine the locale from the authenticated user.
If None is returned, we fall back to get_browser_locale().
This method should return a tornado.locale.Locale object, most likely obtained via a call like
tornado.locale.get("en")
- property locale: Locale#
The locale for the current session.
Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the
Accept-Language
header.
- log_exception(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType]) None #
Override to customize logging of uncaught exceptions.
By default logs instances of HTTPError as warnings without stack traces (on the
tornado.general
logger), and all other exceptions as errors with stack traces (on thetornado.application
logger).New in version 3.1.
- on_connection_close() None #
Called in async handlers if the client closed the connection.
Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.
Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
- on_finish() None #
Called after the end of a request.
Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare.
on_finish
may not produce any output, as it is called after the response has been sent to the client.
- prepare() Optional[Awaitable[None]] #
Called at the beginning of a request before get/post/etc.
Override this method to perform common initialization regardless of the request method.
Asynchronous support: Use
async def
or decorate this method with .gen.coroutine to make it asynchronous. If this method returns anAwaitable
execution will not proceed until theAwaitable
is done.New in version 3.1: Asynchronous support.
- redirect(url: str, permanent: bool = False, status: Optional[int] = None) None #
Sends a redirect to the given (optionally relative) URL.
If the
status
argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on thepermanent
argument. The default is 302 (temporary).
- render(template_name: str, **kwargs: Any) Future[None] #
Renders the template with the given arguments as the response.
render()
callsfinish()
, so no other output methods can be called after it.Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.
Changed in version 5.1: Now returns a .Future instead of
None
.
- render_embed_css(css_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded css for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_embed_js(js_embed: Iterable[bytes]) bytes #
Default method used to render the final embedded js for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_css(css_files: Iterable[str]) str #
Default method used to render the final css links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_linked_js(js_files: Iterable[str]) str #
Default method used to render the final js links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
- render_string(template_name: str, **kwargs: Any) bytes #
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
- require_setting(name: str, feature: str = 'this feature') None #
Raises an exception if the given app setting is not defined.
- reverse_url(name: str, *args: Any) str #
Alias for Application.reverse_url.
- send_error(status_code: int = 500, **kwargs: Any) None #
Sends the given HTTP error code to the browser.
If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.
Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.
- set_cookie(name: str, value: Union[str, bytes], domain: Optional[str] = None, expires: Optional[Union[float, Tuple, datetime]] = None, path: str = '/', expires_days: Optional[float] = None, *, max_age: Optional[int] = None, httponly: bool = False, secure: bool = False, samesite: Optional[str] = None, **kwargs: Any) None #
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 #
Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom
Server
header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.
- set_etag_header() None #
Sets the response’s Etag header using
self.compute_etag()
.Note: no header will be set if
compute_etag()
returnsNone
.This method is called automatically when the request is finished.
- set_header(name: str, value: Union[bytes, str, int, Integral, datetime]) None #
Sets the given response header name and value.
All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the
Date
header).
- set_secure_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_signed_cookie
to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.
- set_signed_cookie(name: str, value: Union[str, bytes], expires_days: Optional[float] = 30, version: Optional[int] = None, **kwargs: Any) None #
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 themax_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
toset_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: Optional[str] = None) None #
Sets the status code for our response.
- Parameters:
status_code (int) – Response status code.
reason (str) – Human-readable reason phrase describing the status code. If
None
, it will be filled in from http.client.responses or “Unknown”.
Changed in version 5.0: No longer validates that the response code is in http.client.responses.
- property settings: Dict[str, Any]#
An alias for self.application.settings <Application.settings>.
- static_url(path: str, include_host: Optional[bool] = None, **kwargs: Any) str #
Returns a static URL for the given relative static file path.
This method requires you set the
static_path
setting in your application (which specifies the root directory of your static files).This method returns a versioned url (by default appending
?v=<signature>
), which allows the static files to be cached indefinitely. This can be disabled by passinginclude_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 aninclude_host
attribute, that value will be used as the default for all static_url calls that do not passinclude_host
as a keyword argument.
- write(chunk: Union[str, bytes, dict]) None #
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be
application/json
. (if you want to send JSON as a differentContent-Type
, callset_header
after callingwrite()
).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 #
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 askwargs["exc_info"]
. Note that this exception may not be the “current” exception for purposes of methods likesys.exc_info()
ortraceback.format_exc
.
- xsrf_form_html() str #
An HTML
<input/>
element to be included with all POST forms.It defines the
_xsrf
input value, which we check on all POST requests to prevent cross-site request forgery. If you have set thexsrf_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 thesecure
andhttponly
flags on the_xsrf
cookie.
loading
Module#
This module contains functionality to make any Panel component look like it is loading and disabled.
- panel.io.loading.start_loading_spinner(*objects)[source]#
Changes the appearance of the specified panel objects to indicate that they are loading.
This is done by
adding a small spinner on top
graying out the panel
disabling the panel
and changing the mouse cursor to a spinner when hovering over the panel
- Parameters:
objects (tuple) – The panels to add the loading indicator to.
location
Module#

Defines the Location widget which allows changing the href of the window.
- class panel.io.location.Location(**params)[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.
href
= param.String(constant=True, default=’’, label=’Href’, readonly=True)The full url, e.g. ‘https://localhost:80?color=blue#interact’
hostname
= param.String(constant=True, default=’’, label=’Hostname’, readonly=True)hostname in window.location e.g. ‘panel.holoviz.org’
pathname
= param.String(default=’’, label=’Pathname’, regex=’^$|[\/].*$’)pathname in window.location e.g. ‘/user_guide/Interact.html’
protocol
= param.String(constant=True, default=’’, label=’Protocol’, readonly=True)protocol in window.location e.g. ‘http:’ or ‘https:’
port
= param.String(constant=True, default=’’, label=’Port’, readonly=True)port in window.location e.g. ‘80’
search
= param.String(default=’’, label=’Search’, regex=’^$|\?’)search in window.location e.g. ‘?color=blue’
hash
= param.String(default=’’, label=’Hash’, regex=’^$|#’)hash in window.location e.g. ‘#interact’
reload
= param.Boolean(bounds=(0, 1), default=False, label=’Reload’)Reload the page when the location is updated. For multipage apps this should be set to True, For single page apps this should be set to False
- get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model [source]#
Returns the root model and applies pre-processing hooks
- Parameters:
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
- Return type:
Returns the bokeh model corresponding to this panel object
- sync(parameterized: param.Parameterized, parameters: Optional[List[str] | Dict[str, str]] = None, on_error: Optional[Callable[[Dict[str, Any]], None]] = None) None [source]#
Syncs the parameters of a Parameterized object with the query parameters in the URL. If no parameters are supplied all parameters except the name are synced.
- Parameters:
(param.Parameterized) (parameterized) – The Parameterized object to sync query parameters with
dict) (parameters (list or) – A list or dictionary specifying parameters to sync. If a dictionary is supplied it should define a mapping from the Parameterized’s parameters to the names of the query parameters.
on_error ((callable):) – Callback when syncing Parameterized with URL parameters fails. The callback is passed a dictionary of parameter values, which could not be applied.
- unsync(parameterized: Parameterized, parameters: Optional[List[str]] = None) None [source]#
Unsyncs the parameters of the Parameterized with the query params in the URL. If no parameters are supplied all parameters except the name are unsynced.
- Parameters:
(param.Parameterized) (parameterized) – The Parameterized object to unsync query parameters with
(list) (parameters) – A list of parameters to unsync.
logging
Module#
markdown
Module#

- class panel.io.markdown.MarkdownHandler(*args, **kwargs)[source]#
Bases:
CodeHandler
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)#
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
- Parameters:
doc (Document) – A Bokeh Document to update in-place
- Returns:
Document
- on_server_loaded(server_context: ServerContext) None #
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.
- Parameters:
server_context (ServerContext) –
- on_server_unloaded(server_context: ServerContext) None #
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.
- Parameters:
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 #
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.- Parameters:
session_context (SessionContext) –
- async on_session_destroyed(session_context: SessionContext) None #
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.
- Parameters:
session_context (SessionContext) –
- process_request(request: HTTPServerRequest) dict[str, Any] #
Processes incoming HTTP request returning a dictionary of additional data to add to the session_context.
- Parameters:
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 #
Return a path to app-specific static resources, if applicable.
- url_path() str | None #
The last path component for the basename of the configured filename.
mime_render
Module#

Utilities for executing Python code and rendering the resulting output using a similar MIME-type based rendering system as implemented by IPython.
Attempts to limit the actual MIME types that have to be rendered on to a minimum simplifying frontend implementation:
application/bokeh: Model JSON representation
text/plain: HTML escaped string output
text/html: HTML code to insert into the DOM
- class panel.io.mime_render.WriteCallbackStream(on_write=None, escape=True)[source]#
Bases:
StringIO
- close()#
Close the IO object.
Attempting any further operation after the object is closed will raise a ValueError.
This method has no effect if the file is already closed.
- detach()#
Separate the underlying buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIO is in an unusable state.
- encoding#
Encoding of the text stream.
Subclasses should override.
- errors#
The error setting of the decoder or encoder.
Subclasses should override.
- fileno()#
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush()#
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- getvalue()#
Retrieve the entire contents of the object.
- isatty()#
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- newlines#
- read(size=-1, /)#
Read at most size characters, returned as a string.
If the argument is negative or omitted, read until EOF is reached. Return an empty string at EOF.
- readable()#
Returns True if the IO object can be read.
- readline(size=-1, /)#
Read until newline or EOF.
Returns an empty string if EOF is hit immediately.
- readlines(hint=-1, /)#
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
- seek(pos, whence=0, /)#
Change stream position.
- Seek to character offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0; 1 Current position - pos must be 0; 2 End of stream - pos must be 0.
Returns the new absolute position.
- seekable()#
Returns True if the IO object can be seeked.
- tell()#
Tell the current file position.
- truncate(pos=None, /)#
Truncate size to pos.
The pos argument defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new absolute position.
- writable()#
Returns True if the IO object can be written.
- write(s)[source]#
Write string to file.
Returns the number of characters written, which is always equal to the length of the string.
- writelines(lines, /)#
Write a list of lines to stream.
Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
- panel.io.mime_render.exec_with_return(code: str, global_context: Optional[Dict[str, Any]] = None, stdout: Optional[Any] = None, stderr: Optional[Any] = None) Any [source]#
Executes a code snippet and returns the resulting output of the last line.
- Parameters:
code (str) – The code to execute
global_context (Dict[str, Any]) – The globals to inject into the execution context.
stdout (io.StringIO) – The stream to redirect stdout to.
stderr (io.StringIO) – The stream to redirect stderr to.
- Return type:
The return value of the executed code.
- panel.io.mime_render.find_imports(code: str) List[str] [source]#
Finds the imports in a string of code.
- Parameters:
code (str) – the Python code to run.
- Returns:
A list of module names that are imported in the code.
- Return type:
List[str]
Examples
>>> code = "import numpy as np; import scipy.stats" >>> find_imports(code) ['numpy', 'scipy']
model
Module#

Utilities for manipulating bokeh models.
- panel.io.model.add_to_doc(obj: Model, doc: Document, hold: bool = False)[source]#
Adds a model to the supplied Document removing it from any existing Documents.
- panel.io.model.bokeh_repr(obj: Model, depth: int = 0, ignored: Optional[Iterable[str]] = None) str [source]#
Returns a string repr for a bokeh model, useful for recreating panel objects using pure bokeh.
- class panel.io.model.comparable_array[source]#
Bases:
ndarray
Array subclass that allows comparisons.
- T#
View of the transposed array.
Same as
self.transpose()
.Examples
>>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.T array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.T array([1, 2, 3, 4])
See also
- all(axis=None, out=None, keepdims=False, *, where=True)#
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See also
numpy.all
equivalent function
- any(axis=None, out=None, keepdims=False, *, where=True)#
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See also
numpy.any
equivalent function
- argmax(axis=None, out=None, *, keepdims=False)#
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See also
numpy.argmax
equivalent function
- argmin(axis=None, out=None, *, keepdims=False)#
Return indices of the minimum values along the given axis.
Refer to numpy.argmin for detailed documentation.
See also
numpy.argmin
equivalent function
- argpartition(kth, axis=-1, kind='introselect', order=None)#
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation.
New in version 1.8.0.
See also
numpy.argpartition
equivalent function
- argsort(axis=-1, kind=None, order=None)#
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
numpy.argsort
equivalent function
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)#
Copy of the array, cast to a specified type.
- Parameters:
dtype (str or dtype) – Typecode or data-type to which the array is cast.
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ means any data conversions may be done.
subok (bool, optional) – If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
copy (bool, optional) – By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
- Returns:
arr_t – Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
- Return type:
ndarray
Notes
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.
- Raises:
ComplexWarning – When casting from complex to float or int. To avoid this, one should use
a.real.astype(t)
.
Examples
>>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5])
>>> x.astype(int) array([1, 2, 2])
- base#
Base object if memory is from some other object.
Examples
The base of an array that owns its memory is None:
>>> x = np.array([1,2,3,4]) >>> x.base is None True
Slicing creates a view, whose memory is shared with x:
>>> y = x[2:] >>> y.base is x True
- byteswap(inplace=False)#
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
- Parameters:
inplace (bool, optional) – If
True
, swap bytes in-place, default isFalse
.- Returns:
out – The byteswapped array. If inplace is
True
, this is a view to self.- Return type:
ndarray
Examples
>>> A = np.array([1, 256, 8755], dtype=np.int16) >>> list(map(hex, A)) ['0x1', '0x100', '0x2233'] >>> A.byteswap(inplace=True) array([ 256, 1, 13090], dtype=int16) >>> list(map(hex, A)) ['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped
>>> A = np.array([b'ceg', b'fac']) >>> A.byteswap() array([b'ceg', b'fac'], dtype='|S3')
A.newbyteorder().byteswap()
produces an array with the same valuesbut different representation in memory
>>> A = np.array([1, 2, 3]) >>> A.view(np.uint8) array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) >>> A.newbyteorder().byteswap(inplace=True) array([1, 2, 3]) >>> A.view(np.uint8) array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
- choose(choices, out=None, mode='raise')#
Use an index array to construct a new array from a set of choices.
Refer to numpy.choose for full documentation.
See also
numpy.choose
equivalent function
- clip(min=None, max=None, out=None, **kwargs)#
Return an array whose values are limited to
[min, max]
. One of max or min must be given.Refer to numpy.clip for full documentation.
See also
numpy.clip
equivalent function
- compress(condition, axis=None, out=None)#
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
numpy.compress
equivalent function
- conj()#
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugate
equivalent function
- conjugate()#
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugate
equivalent function
- copy(order='C')#
Return a copy of the array.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and
numpy.copy()
are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
numpy.copy
Similar function with different default behavior
numpy.copyto
Notes
This function is the preferred method for creating an array copy. The function
numpy.copy()
is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.Examples
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x array([[0, 0, 0], [0, 0, 0]])
>>> y array([[1, 2, 3], [4, 5, 6]])
>>> y.flags['C_CONTIGUOUS'] True
- ctypes#
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
- Parameters:
None –
- Returns:
c – Possessing attributes data, shape, strides, etc.
- Return type:
Python object
See also
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
- _ctypes.data
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as
self._array_interface_['data'][0]
.Note that unlike
data_as
, a reference will not be kept to the array: code likectypes.c_void_p((a + b).ctypes.data)
will result in a pointer to a deallocated array, and should be spelt(a + b).ctypes.data_as(ctypes.c_void_p)
- _ctypes.shape
A ctypes array of length self.ndim where the basetype is the C-integer corresponding to
dtype('p')
on this platform (see ~numpy.ctypeslib.c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.- Type:
(c_intp*self.ndim)
- _ctypes.strides
A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
- Type:
(c_intp*self.ndim)
- _ctypes.data_as(obj)
Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_
is equivalent toself.data_as(ctypes.c_void_p)
. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data:self.data_as(ctypes.POINTER(ctypes.c_double))
.The returned pointer will keep a reference to the array.
- _ctypes.shape_as(obj)
Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short)
.
- _ctypes.strides_as(obj)
Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong)
.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the
as_parameter
attribute which will return an integer equal to the data attribute.Examples
>>> import ctypes >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) >>> x array([[0, 1], [2, 3]], dtype=int32) >>> x.ctypes.data 31962608 # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents c_uint(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents c_ulong(4294967296) >>> x.ctypes.shape <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary >>> x.ctypes.strides <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
- cumprod(axis=None, dtype=None, out=None)#
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
See also
numpy.cumprod
equivalent function
- cumsum(axis=None, dtype=None, out=None)#
Return the cumulative sum of the elements along the given axis.
Refer to numpy.cumsum for full documentation.
See also
numpy.cumsum
equivalent function
- data#
Python buffer object pointing to the start of the array’s data.
- diagonal(offset=0, axis1=0, axis2=1)#
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to
numpy.diagonal()
for full documentation.See also
numpy.diagonal
equivalent function
- dtype#
Data-type of the array’s elements.
Warning
Setting
arr.dtype
is discouraged and may be deprecated in the future. Setting will replace thedtype
without modifying the memory (see also ndarray.view and ndarray.astype).- Parameters:
None –
- Returns:
d
- Return type:
numpy dtype object
See also
ndarray.astype
Cast the values contained in the array to a new data-type.
ndarray.view
Create a view of the same data but a different data-type.
numpy.dtype
Examples
>>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int32') >>> type(x.dtype) <type 'numpy.dtype'>
- dump(file)#
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
- Parameters:
file (str or Path) –
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
- dumps()#
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.
- Parameters:
None –
- fill(value)#
Fill the array with a scalar value.
- Parameters:
value (scalar) – All elements of a will be assigned this value.
Examples
>>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([1., 1.])
Fill expects a scalar value and always behaves the same as assigning to a single array element. The following is a rare example where this distinction is important:
>>> a = np.array([None, None], dtype=object) >>> a[0] = np.array(3) >>> a array([array(3), None], dtype=object) >>> a.fill(np.array(3)) >>> a array([array(3), array(3)], dtype=object)
Where other forms of assignments will unpack the array being assigned:
>>> a[...] = np.array(3) >>> a array([3, 3], dtype=object)
- flags#
Information about the memory layout of the array.
- C_CONTIGUOUS(C)#
The data is in a single, C-style contiguous segment.
- F_CONTIGUOUS(F)#
The data is in a single, Fortran-style contiguous segment.
- OWNDATA(O)#
The array owns the memory it uses or borrows it from another object.
- WRITEABLE(W)#
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
- ALIGNED(A)#
The data and all elements are aligned appropriately for the hardware.
- WRITEBACKIFCOPY(X)#
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
- FNC#
F_CONTIGUOUS and not C_CONTIGUOUS.
- FORC#
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
- BEHAVED(B)#
ALIGNED and WRITEABLE.
- CARRAY(CA)#
BEHAVED and C_CONTIGUOUS.
- FARRAY(FA)#
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
Notes
The flags object can be accessed dictionary-like (as in
a.flags['WRITEABLE']
), or by using lowercased attribute names (as ina.flags.writeable
). Short flag names are only supported in dictionary access.Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
WRITEBACKIFCOPY can only be set
False
.ALIGNED can only be set
True
if the data is truly aligned.WRITEABLE can only be set
True
if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string.
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension
arr.strides[dim]
may be arbitrary ifarr.shape[dim] == 1
or the array has no elements. It does not generally hold thatself.strides[-1] == self.itemsize
for C-style contiguous arrays orself.strides[0] == self.itemsize
for Fortran-style contiguous arrays is true.
- flat#
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
Examples
>>> x = np.arange(1, 7).reshape(2, 3) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> x.flat[3] 4 >>> x.T array([[1, 4], [2, 5], [3, 6]]) >>> x.T.flat[3] 5 >>> type(x.flat) <class 'numpy.flatiter'>
An assignment example:
>>> x.flat = 3; x array([[3, 3, 3], [3, 3, 3]]) >>> x.flat[[1,4]] = 1; x array([[3, 1, 3], [3, 1, 3]])
- flatten(order='C')#
Return a copy of the array collapsed into one dimension.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
- Returns:
y – A copy of the input array, flattened to one dimension.
- Return type:
ndarray
Examples
>>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4])
- getfield(dtype, offset=0)#
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
- Parameters:
dtype (str or dtype) – The data type of the view. The dtype size of the view can not be larger than that of the array itself.
offset (int) – Number of bytes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2) >>> x[1, 1] = 2 + 4.j >>> x array([[1.+1.j, 0.+0.j], [0.+0.j, 2.+4.j]]) >>> x.getfield(np.float64) array([[1., 0.], [0., 2.]])
By choosing an offset of 8 bytes we can select the complex part of the array for our view:
>>> x.getfield(np.float64, offset=8) array([[1., 0.], [0., 4.]])
- imag#
The imaginary part of the array.
Examples
>>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64')
- item(*args)#
Copy an element of an array to a standard Python scalar and return it.
- Parameters:
*args (Arguments (variable number and type)) –
none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.
- Returns:
z – A copy of the specified element of the array as a suitable Python scalar
- Return type:
Standard Python scalar object
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.
Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.item(3) 1 >>> x.item(7) 0 >>> x.item((0, 1)) 2 >>> x.item((2, 2)) 1
- itemset(*args)#
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then,
a.itemset(*args)
is equivalent to but faster thana[args] = item
. The item should be a scalar value and args must select a single item in the array a.- Parameters:
*args (Arguments) – If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.
Notes
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.
Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[2, 2, 6], [1, 0, 6], [1, 0, 9]])
- itemsize#
Length of one array element in bytes.
Examples
>>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16
- max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)#
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See also
numpy.amax
equivalent function
- mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)#
Returns the average of the array elements along given axis.
Refer to numpy.mean for full documentation.
See also
numpy.mean
equivalent function
- min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)#
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See also
numpy.amin
equivalent function
- nbytes#
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
Examples
>>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480