panel.io.resources module#

Patches bokeh resources to make it easy to add external JS and CSS resources via the panel.config object.

class panel.io.resources.ResourceComponent[source]#

Bases: object

Mix-in class for components that define a set of resources that have to be resolved.

Methods

resolve_resources([cdn, extras])

Resolves the resources required for this component.

resolve_resources(cdn: bool | t.Literal['auto'] = 'auto', extras: dict[str, dict[str, str]] | None = None) → ResourcesType[source]#

Resolves the resources required for this component.

Parameters:
cdn: bool | Literal[‘auto’]

Whether to load resources from CDN or local server. If set to ‘auto’ value will be automatically determine based on global settings.

extras: dict[str, dict[str, str]] | None

Additional resources to add to the bundle. Valid resource types include js, js_modules and css.

Returns:
Dictionary containing JS and CSS resources.
class panel.io.resources.Resources(*args, absolute=False, notebook=False, **kwargs)[source]#

Bases: Resources

Attributes:
css_files
css_raw
dist_dir
js_files
js_module_exports
js_modules
js_raw
render_js
resource_declarations

Methods

adjust_paths(resources)

Computes relative and absolute paths for resources.

clone(*[, components])

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

extra_resources(resources, resource_type)

Adds resources for ReactiveHTML components.

jupyter_cdn_map()

Pairs of paths relative to the Jupyter server extension root and the CDN urls serving the same files.

from_bokeh

adjust_paths(resources)[source]#

Computes relative and absolute paths for resources.

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

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

extra_resources(resources, resource_type)[source]#

Adds resources for ReactiveHTML components.

jupyter_cdn_map() → list[tuple[str, str]][source]#

Pairs of paths relative to the Jupyter server extension root and the CDN urls serving the same files.

Lets the notebook bootstrap load the files from the CDN when the endpoint cannot serve them, e.g. in an exported notebook.

panel.io.resources.component_resource_path(component, attr: str, path: str | PathLike) → str[source]#

Generates a canonical URL for a component resource.

To be used in conjunction with the panel.io.server.ComponentResourceHandler which allows dynamically resolving resources defined on components.

panel.io.resources.dedupe_template_resources(template_resources: ResourcesType, bundle: BkBundle) → ResourcesType[source]#

Drops template resources the page already loads through the bundle, or earlier in the template resources, keeping the remaining order.

A design’s resources are declared on the Document bundle and on the template rendering it, so without this a template page loads e.g. the fast-components module and the font stylesheet twice.

panel.io.resources.extension_cdn_map() → list[tuple[str, str]][source]#

Pairs of server extension paths (static/extensions/<name>/) and the CDN urls serving the same files, for Panel and every extension with a CDN.

panel.io.resources.extension_declared(cls: type) → bool[source]#

Whether a model class’ extension was declared in this session.

Classes that do not belong to an extension always pass, as does every class when there is no session to ask (a notebook, or rendering outside a document), which is what keeps those paths eager.

panel.io.resources.get_env()[source]#

Get the correct Jinja2 Environment, also for frozen scripts.

panel.io.resources.get_notebook_resources() → bool[source]#

Whether resource urls should use the Jupyter extension endpoint.

panel.io.resources.get_resource_mode() → MODES[source]#

The mode urls are currently being resolved for.

Has to be read through a function: set_resource_mode rebinds the module global, so a module that imported the name would keep whatever it happened to be at import time.

panel.io.resources.imported_stylesheet(url: str) → ImportedStyleSheet[source]#

Returns an ImportedStyleSheet for the url. Within a stylesheet_scope the stylesheet shared on the Document is returned if there is one, since every component would otherwise construct its own only for it to be replaced by the shared one when the stylesheets are resolved.

class panel.io.resources.json_dumps(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#

Bases: JSONEncoder

default(obj)[source]#

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
panel.io.resources.jupyter_endpoint_available() → bool[source]#

Whether notebook output loads resources from Panel’s Jupyter server extension, as selected by config.notebook_resources.

By default that is the case if this process was launched by a Jupyter server that serves the extension.

panel.io.resources.jupyter_endpoint_root() → str[source]#

The root url of the Jupyter server extension, e.g. /panel-preview/.

panel.io.resources.loaded_custom_classes() → list[type][source]#

The ReactiveHTML/ReactiveESM classes whose extension is loaded.

panel.io.resources.model_registry_key() → tuple[type, ...][source]#

Identifies the current contents of Bokeh’s model registry.

Caches derived from the registry key on this rather than on its size, since tests (and Model.clear_extensions) unregister and re-register classes, which leaves the size unchanged.

panel.io.resources.module_tags(js_modules: list[str], js_module_exports: dict[str, str]) → list[tuple[str, str | None]][source]#

Pairs each module url with the global its namespace is exported as.

A module that has an export wrapper is loaded by that wrapper’s import, so emitting a bare <script type="module" src> for it as well leaves two tags for one url. Pairing them keeps every module in the order js_modules gives, which is the order they execute in.

panel.io.resources.notebook_extension_url(path: str) → str | None[source]#

Resolves a static/extensions/<name>/... path against the Jupyter server extension when notebook output is served by it.

Returns None if the endpoint is not in use, e.g. in a server session, with inlined resources or when the endpoint is not available.

panel.io.resources.patch_model_css(root: Model, dist_url: str)[source]#

Temporary patch for Model.css property used by Panel to provide stylesheets for components.

ALERT: Should find better solution before official Bokeh 3.x compatible release

panel.io.resources.process_raw_css(raw_css: list[str]) → list[str][source]#

Converts old-style Bokeh<3 compatible CSS to Bokeh 3 compatible CSS.

panel.io.resources.remember(cache: dict, key: Hashable, value: Any, limit: int = 32) → Any[source]#

Stores a value in a bounded cache, evicting the oldest entry first.

panel.io.resources.resolve_custom_path(obj, path: str | PathLike, relative: bool = False) → Path | None[source]#

Attempts to resolve a path relative to some component.

Parameters:
obj: type | object

The component to resolve the path relative to.

path: str | os.PathLike

Absolute or relative path to a resource.

relative: bool

Whether to return a relative path.

Returns:
path: pathlib.Path | None
panel.io.resources.resolve_resource_cdn(resource: str | PathLike) → str | PathLike[source]#

Resolves a CDN URL given a file path that is relative to an extension dist directory.

panel.io.resources.resolve_stylesheet(cls, stylesheet: str, attribute: str | None = None)[source]#

Resolves a stylesheet definition, e.g. originating on a component Reactive._stylesheets or a Design.modifiers attribute. Stylesheets may be defined as one of the following:

  • Absolute URL defined with http(s) protocol

  • A path relative to the component

  • A raw css string

Parameters:
cls: type | object

Object or class defining the stylesheet

stylesheet: str

The stylesheet definition

panel.io.resources.set_default_resource_mode(mode: MODES, *, notebook: bool = False)[source]#

Sets the mode urls are resolved for outside a set_resource_mode block.

The module default is server, i.e. relative urls into the static endpoint Panel itself serves, which is the right guess for an application but wrong for a notebook: the page is served by Jupyter from an unrelated url, so static/extensions/panel/... resolves against /lab/tree/<dir>/ and 404s. It cannot be handled by a context manager either, because components created in a later cell resolve their resources long after pn.extension() returned.

panel.io.resources.shared_inline_stylesheet(css: str, cache: dict[str, InlineStyleSheet], doc: Document) → InlineStyleSheet[source]#

Returns the InlineStyleSheet holding the CSS on a Document, creating it on first use so every model on the Document references the same instance. A cached stylesheet is replaced if it was destroyed along with a previous Document or is still attached to another one.

panel.io.resources.sorted_model_classes() → list[type][source]#

The registered model classes sorted by qualified name.

panel.io.resources.stylesheet_scope(doc: Document | None)[source]#

Makes the ImportedStyleSheets already shared by the models on a Document available to imported_stylesheet while the properties of a component rendered into that Document are computed.

panel.io.resources.stylesheet_url(stylesheet: ImportedStyleSheet) → str | None[source]#

Returns the url of an ImportedStyleSheet or None if it is unset.

Bokeh clears the property values of every model on a Document when the Document is destroyed at the end of a session. An ImportedStyleSheet that outlives the Document it was rendered into, e.g. because it is held in a cache, is therefore left without a url and reading it raises an UnsetValueError. Such a stylesheet must never be reused since it breaks both model creation and the serialization of the Document it is added to.