response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Create a Create a ``DataSpec`` dict to generate a ``Stack`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.vbar(bottom=stack("sales", "marketing"), ...
will generate a ``Stack`` that sums the ``"sales"`` and ``"marketing"``
columns of a data source, and use those values as the ``top``
coordinate for a ``VBar``. | def stack(*fields: str) -> Expr:
''' Create a Create a ``DataSpec`` dict to generate a ``Stack`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.vbar(bottom=stack("sales", "marketing"), ...
will generate a ``Stack`` that sums the ``"sales"`` and ``"marketing"``
columns of a data source, and use those values as the ``top``
coordinate for a ``VBar``.
'''
return Expr(Stack(fields=fields)) |
Create a ``DataSpec`` dict that applies an arbitrary client-side
``Transform`` to a ``ColumnDataSource`` column.
Args:
field_name (str) : A field name to configure ``DataSpec`` with
transform (Transform) : A transforms to apply to that field
Returns:
Field | def transform(field_name: str, transform: Transform) -> Field:
''' Create a ``DataSpec`` dict that applies an arbitrary client-side
``Transform`` to a ``ColumnDataSource`` column.
Args:
field_name (str) : A field name to configure ``DataSpec`` with
transform (Transform) : A transforms to apply to that field
Returns:
Field
'''
return Field(field_name, transform) |
Print the Bokeh license to the console.
Returns:
None | def license():
''' Print the Bokeh license to the console.
Returns:
None
'''
from pathlib import Path
with open(Path(__file__).parent / 'LICENSE.txt') as lic:
print(lic.read()) |
Execute the "bokeh" command line program.
| def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see pyproject.toml)
_main(sys.argv) |
Calls any on_session_destroyed callbacks defined on the Document | def _on_session_destroyed(session_context: SessionContext) -> None:
'''
Calls any on_session_destroyed callbacks defined on the Document
'''
callbacks = session_context._document.session_destroyed_callbacks
session_context._document.session_destroyed_callbacks = set()
for callback in callbacks:
try:
callback(session_context)
except Exception as e:
log.warning("DocumentLifeCycleHandler on_session_destroyed "
f"callback {callback} failed with following error: {e}")
if callbacks:
# If any session callbacks were defined garbage collect after deleting all references
del callback
del callbacks
import gc
gc.collect() |
Record an exception and details on a Handler.
| def handle_exception(handler: Handler | CodeRunner, e: Exception) -> None:
''' Record an exception and details on a Handler.
'''
handler._failed = True
handler._error_detail = traceback.format_exc()
_, _, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
basename = os.path.basename(filename)
handler._error = f"{e}\nFile {basename!r}, line {line_number}, in {func}:\n{txt}" |
Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the server.
If you don't plan to modify ``session.document`` you probably
don't need to use this function; instead you can directly
``show_session()`` or ``server_session()`` without downloading
the session's document into your process first. It's much
more efficient to avoid downloading the session if you don't need
to.
In a production scenario, the ``session_id`` should be
unique for each browser tab, which keeps users from
stomping on each other. It's neither scalable nor secure to
use predictable session IDs or to share session IDs across
users.
For a notebook running on a single machine, ``session_id``
could be something human-readable such as ``"default"`` for
convenience.
If you allow ``pull_session()`` to generate a unique
``session_id``, you can obtain the generated ID with the
``id`` property on the returned ``ClientSession``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop (``tornado.ioloop.IOLoop``, optional) :
The ``IOLoop`` to use for the websocket
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Note that should only be provided when pulling new sessions.
If ``session_id`` is not None, or a session with ``session_id``
already exists, these arguments will have no effect.
max_message_size (int, optional) :
Configure the Tornado max websocket message size.
(default: 20 MB)
Returns:
ClientSession :
A new ``ClientSession`` connected to the server | def pull_session(session_id: ID | None = None, url: str = "default", io_loop: IOLoop | None = None,
arguments: dict[str, str] | None = None, max_message_size: int = 20*1024*1024) -> ClientSession:
''' Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the server.
If you don't plan to modify ``session.document`` you probably
don't need to use this function; instead you can directly
``show_session()`` or ``server_session()`` without downloading
the session's document into your process first. It's much
more efficient to avoid downloading the session if you don't need
to.
In a production scenario, the ``session_id`` should be
unique for each browser tab, which keeps users from
stomping on each other. It's neither scalable nor secure to
use predictable session IDs or to share session IDs across
users.
For a notebook running on a single machine, ``session_id``
could be something human-readable such as ``"default"`` for
convenience.
If you allow ``pull_session()`` to generate a unique
``session_id``, you can obtain the generated ID with the
``id`` property on the returned ``ClientSession``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop (``tornado.ioloop.IOLoop``, optional) :
The ``IOLoop`` to use for the websocket
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Note that should only be provided when pulling new sessions.
If ``session_id`` is not None, or a session with ``session_id``
already exists, these arguments will have no effect.
max_message_size (int, optional) :
Configure the Tornado max websocket message size.
(default: 20 MB)
Returns:
ClientSession :
A new ``ClientSession`` connected to the server
'''
coords = SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(
session_id=session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, arguments=arguments, max_message_size=max_message_size)
session.pull()
return session |
Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and changes made on the
client side will be synced to the server.
In a production scenario, the ``session_id`` should be unique for each
browser tab, which keeps users from stomping on each other. It's neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
If you allow ``push_session()`` to generate a unique ``session_id``, you
can obtain the generated ID with the ``id`` property on the returned
``ClientSession``.
Args:
document : (bokeh.document.Document)
The document to be pushed and set as session.document
session_id : (string, optional)
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop : (tornado.ioloop.IOLoop, optional)
The IOLoop to use for the websocket
max_message_size (int, optional) :
Configure the Tornado max websocket message size.
(default: 20 MB)
Returns:
ClientSession
A new ClientSession connected to the server | def push_session(document: Document, session_id: ID | None = None, url: str = "default",
io_loop: IOLoop | None = None, max_message_size: int = 20*1024*1024) -> ClientSession:
''' Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and changes made on the
client side will be synced to the server.
In a production scenario, the ``session_id`` should be unique for each
browser tab, which keeps users from stomping on each other. It's neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
If you allow ``push_session()`` to generate a unique ``session_id``, you
can obtain the generated ID with the ``id`` property on the returned
``ClientSession``.
Args:
document : (bokeh.document.Document)
The document to be pushed and set as session.document
session_id : (string, optional)
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop : (tornado.ioloop.IOLoop, optional)
The IOLoop to use for the websocket
max_message_size (int, optional) :
Configure the Tornado max websocket message size.
(default: 20 MB)
Returns:
ClientSession
A new ClientSession connected to the server
'''
coords = SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(session_id=coords.session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, max_message_size=max_message_size)
session.push(document)
return session |
Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
session (ClientSession, optional) : session to get session ID and server URL from
If you specify this, you don't need to specify session_id and url
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the :doc:`webbrowser <python:library/webbrowser>`
module documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window. | def show_session(
session_id: ID | None = None,
url: str = "default",
session: ClientSession | None = None,
browser: str | None = None,
new: BrowserTarget = "tab",
controller: BrowserLike | None = None) -> None:
''' Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
session (ClientSession, optional) : session to get session ID and server URL from
If you specify this, you don't need to specify session_id and url
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the :doc:`webbrowser <python:library/webbrowser>`
module documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window.
'''
if session is not None:
server_url = server_url_for_websocket_url(session._connection.url)
session_id = session.id
else:
coords = SessionCoordinates(session_id=session_id, url=url)
server_url = coords.url
session_id = coords.session_id
if controller is None:
from bokeh.util.browser import get_browser_controller
controller = get_browser_controller(browser=browser)
controller.open(server_url + "?bokeh-session-id=" + quote_plus(session_id),
new=NEW_PARAM[new]) |
Convert an ``ws(s)`` URL for a Bokeh server into the appropriate
``http(s)`` URL for the websocket endpoint.
Args:
url (str):
An ``ws(s)`` URL ending in ``/ws``
Returns:
str:
The corresponding ``http(s)`` URL.
Raises:
ValueError:
If the input URL is not of the proper form. | def server_url_for_websocket_url(url: str) -> str:
''' Convert an ``ws(s)`` URL for a Bokeh server into the appropriate
``http(s)`` URL for the websocket endpoint.
Args:
url (str):
An ``ws(s)`` URL ending in ``/ws``
Returns:
str:
The corresponding ``http(s)`` URL.
Raises:
ValueError:
If the input URL is not of the proper form.
'''
if url.startswith("ws:"):
reprotocoled = "http" + url[2:]
elif url.startswith("wss:"):
reprotocoled = "https" + url[3:]
else:
raise ValueError("URL has non-websocket protocol " + url)
if not reprotocoled.endswith("/ws"):
raise ValueError("websocket URL does not end in /ws")
return reprotocoled[:-2] |
Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into
the appropriate ``ws(s)`` URL
Args:
url (str):
An ``http(s)`` URL
Returns:
str:
The corresponding ``ws(s)`` URL ending in ``/ws``
Raises:
ValueError:
If the input URL is not of the proper form. | def websocket_url_for_server_url(url: str) -> str:
''' Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into
the appropriate ``ws(s)`` URL
Args:
url (str):
An ``http(s)`` URL
Returns:
str:
The corresponding ``ws(s)`` URL ending in ``/ws``
Raises:
ValueError:
If the input URL is not of the proper form.
'''
if url.startswith("http:"):
reprotocoled = "ws" + url[4:]
elif url.startswith("https:"):
reprotocoled = "wss" + url[5:]
else:
raise ValueError("URL has unknown protocol " + url)
if reprotocoled.endswith("/"):
return reprotocoled + "ws"
else:
return reprotocoled + "/ws" |
Execute the Bokeh command.
Args:
argv (seq[str]) : a list of command line arguments to process
Returns:
None
The first item in ``argv`` is typically "bokeh", and the second should
be the name of one of the available subcommands:
* :ref:`info <bokeh.command.subcommands.info>`
* :ref:`json <bokeh.command.subcommands.json>`
* :ref:`sampledata <bokeh.command.subcommands.sampledata>`
* :ref:`secret <bokeh.command.subcommands.secret>`
* :ref:`serve <bokeh.command.subcommands.serve>`
* :ref:`static <bokeh.command.subcommands.static>` | def main(argv: Sequence[str]) -> None:
''' Execute the Bokeh command.
Args:
argv (seq[str]) : a list of command line arguments to process
Returns:
None
The first item in ``argv`` is typically "bokeh", and the second should
be the name of one of the available subcommands:
* :ref:`info <bokeh.command.subcommands.info>`
* :ref:`json <bokeh.command.subcommands.json>`
* :ref:`sampledata <bokeh.command.subcommands.sampledata>`
* :ref:`secret <bokeh.command.subcommands.secret>`
* :ref:`serve <bokeh.command.subcommands.serve>`
* :ref:`static <bokeh.command.subcommands.static>`
'''
if len(argv) == 1:
die(f"ERROR: Must specify subcommand, one of: {nice_join(x.name for x in subcommands.all)}")
parser = argparse.ArgumentParser(
prog=argv[0],
epilog="See '<command> --help' to read about a specific subcommand.")
parser.add_argument('-v', '--version', action='version', version=__version__)
subs = parser.add_subparsers(help="Sub-commands")
for cls in subcommands.all:
subparser = subs.add_parser(cls.name, help=cls.help)
subcommand = cls(parser=subparser)
subparser.set_defaults(invoke=subcommand.invoke)
args = parser.parse_args(argv[1:])
try:
ret = args.invoke(args)
except Exception as e:
if settings.dev:
raise
else:
die("ERROR: " + str(e))
if ret is False:
sys.exit(1)
elif ret is not True and isinstance(ret, int) and ret != 0:
sys.exit(ret) |
Print an error message and exit.
This function will call ``sys.exit`` with the given ``status`` and the
process will terminate.
Args:
message (str) : error message to print
status (int) : the exit status to pass to ``sys.exit`` | def die(message: str, status: int = 1) -> Never:
''' Print an error message and exit.
This function will call ``sys.exit`` with the given ``status`` and the
process will terminate.
Args:
message (str) : error message to print
status (int) : the exit status to pass to ``sys.exit``
'''
print(message, file=sys.stderr)
sys.exit(status) |
Return a Bokeh application built using a single handler for a script,
notebook, or directory.
In general a Bokeh :class:`~bokeh.application.application.Application` may
have any number of handlers to initialize |Document| objects for new client
sessions. However, in many cases only a single handler is needed. This
function examines the ``path`` provided, and returns an ``Application``
initialized with one of the following handlers:
* :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
is to a ``.py`` script.
* :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
``path`` is to an ``.ipynb`` Jupyter notebook.
* :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
``path`` is to a directory containing a ``main.py`` script.
Args:
path (str) : path to a file or directory for creating a Bokeh
application.
argv (seq[str], optional) : command line arguments to pass to the
application handler
Returns:
:class:`~bokeh.application.application.Application`
Raises:
RuntimeError
Notes:
If ``path`` ends with a file ``main.py`` then a warning will be printed
regarding running directory-style apps by passing the directory instead. | def build_single_handler_application(path: str, argv: list[str] | None = None) -> Application:
''' Return a Bokeh application built using a single handler for a script,
notebook, or directory.
In general a Bokeh :class:`~bokeh.application.application.Application` may
have any number of handlers to initialize |Document| objects for new client
sessions. However, in many cases only a single handler is needed. This
function examines the ``path`` provided, and returns an ``Application``
initialized with one of the following handlers:
* :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
is to a ``.py`` script.
* :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
``path`` is to an ``.ipynb`` Jupyter notebook.
* :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
``path`` is to a directory containing a ``main.py`` script.
Args:
path (str) : path to a file or directory for creating a Bokeh
application.
argv (seq[str], optional) : command line arguments to pass to the
application handler
Returns:
:class:`~bokeh.application.application.Application`
Raises:
RuntimeError
Notes:
If ``path`` ends with a file ``main.py`` then a warning will be printed
regarding running directory-style apps by passing the directory instead.
'''
argv = argv or []
path = os.path.abspath(os.path.expanduser(path))
handler: Handler
# There are certainly race conditions here if the file/directory is deleted
# in between the isdir/isfile tests and subsequent code. But it would be a
# failure if they were not there to begin with, too (just a different error)
if os.path.isdir(path):
handler = DirectoryHandler(filename=path, argv=argv)
elif os.path.isfile(path):
if path.endswith(".ipynb"):
handler = NotebookHandler(filename=path, argv=argv)
elif path.endswith(".py"):
if path.endswith("main.py"):
warn(DIRSTYLE_MAIN_WARNING)
handler = ScriptHandler(filename=path, argv=argv)
else:
raise ValueError(f"Expected a '.py' script or '.ipynb' notebook, got: '{path}'")
else:
raise ValueError(f"Path for Bokeh server application does not exist: {path}")
if handler.failed:
raise RuntimeError(f"Error loading {path}:\n\n{handler.error}\n{handler.error_detail} ")
application = Application(handler)
return application |
Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
paths (seq[str]) : paths to files or directories for creating Bokeh
applications.
argvs (dict[str, list[str]], optional) : mapping of paths to command
line arguments to pass to the handler for each path
Returns:
dict[str, Application]
Raises:
RuntimeError | def build_single_handler_applications(paths: list[str], argvs: dict[str, list[str]] | None = None) -> dict[str, Application]:
''' Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
paths (seq[str]) : paths to files or directories for creating Bokeh
applications.
argvs (dict[str, list[str]], optional) : mapping of paths to command
line arguments to pass to the handler for each path
Returns:
dict[str, Application]
Raises:
RuntimeError
'''
applications: dict[str, Application] = {}
argvs = argvs or {}
for path in paths:
application = build_single_handler_application(path, argvs.get(path, []))
route = application.handlers[0].url_path()
if not route:
if '/' in applications:
raise RuntimeError(f"Don't know the URL path to use for {path}")
route = '/'
applications[route] = application
return applications |
A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. code-block:: python
with report_server_init_errors(**server_kwargs):
server = Server(applications, **server_kwargs)
If there are any errors (e.g. port or address in already in use) then a
critical error will be logged and the process will terminate with a
call to ``sys.exit(1)`` | def report_server_init_errors(address: str | None = None, port: int | None = None, **kwargs: str) -> Iterator[None]:
''' A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. code-block:: python
with report_server_init_errors(**server_kwargs):
server = Server(applications, **server_kwargs)
If there are any errors (e.g. port or address in already in use) then a
critical error will be logged and the process will terminate with a
call to ``sys.exit(1)``
'''
try:
yield
except OSError as e:
if e.errno == errno.EADDRINUSE:
log.critical("Cannot start Bokeh server, port %s is already in use", port)
elif e.errno == errno.EADDRNOTAVAIL:
log.critical("Cannot start Bokeh server, address '%s' not available", address)
else:
codename = errno.errorcode[e.errno]
log.critical("Cannot start Bokeh server [%s]: %r", codename, e)
sys.exit(1) |
helper method to optionally return module version number or not installed
:param version_or_none:
:return: | def if_installed(version_or_none: str | None) -> str:
''' helper method to optionally return module version number or not installed
:param version_or_none:
:return:
'''
return version_or_none or "(not installed)" |
Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
values (str) : string enumeration values, passed as positional arguments
The order of arguments is the order of the enumeration, and the
first element will be considered the default value when used
to create |Enum| properties.
Keyword Args:
case_sensitive (bool, optional) :
Whether validation should consider case or not (default: True)
quote (bool, optional):
Whether values should be quoted in the string representations
(default: False)
Raises:
ValueError if values empty, if any value is not a string or not unique
Returns:
Enumeration | def enumeration(*values: Any, case_sensitive: bool = True, quote: bool = False) -> Enumeration:
''' Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
values (str) : string enumeration values, passed as positional arguments
The order of arguments is the order of the enumeration, and the
first element will be considered the default value when used
to create |Enum| properties.
Keyword Args:
case_sensitive (bool, optional) :
Whether validation should consider case or not (default: True)
quote (bool, optional):
Whether values should be quoted in the string representations
(default: False)
Raises:
ValueError if values empty, if any value is not a string or not unique
Returns:
Enumeration
'''
if len(values) == 1 and hasattr(values[0], "__args__"):
values = get_args(values[0])
if not (values and all(isinstance(value, str) and value for value in values)):
raise ValueError(f"expected a non-empty sequence of strings, got {nice_join(values)}")
if len(values) != len(set(values)):
raise ValueError(f"enumeration items must be unique, got {nice_join(values)}")
attrs: dict[str, Any] = {value: value for value in values}
attrs.update({
"_values": list(values),
"_default": values[0],
"_case_sensitive": case_sensitive,
"_quote": quote,
})
return type("Enumeration", (Enumeration,), attrs)() |
A decorator to mark abstract base classes derived from |HasProps|.
| def abstract(cls: C) -> C:
''' A decorator to mark abstract base classes derived from |HasProps|.
'''
if not issubclass(cls, HasProps):
raise TypeError(f"{cls.__name__} is not a subclass of HasProps")
_abstract_classes.add(cls)
cls.__doc__ = append_docstring(cls.__doc__, _ABSTRACT_ADMONITION)
return cls |
Convert an object or a serialized representation to a JSON string.
This function accepts Python-serializable objects and converts them to
a JSON string. This function does not perform any advaced serialization,
in particular it won't serialize Bokeh models or numpy arrays. For that,
use :class:`bokeh.core.serialization.Serializer` class, which handles
serialization of all types of objects that may be encountered in Bokeh.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Returns:
str: RFC-8259 JSON string
Examples:
.. code-block:: python
>>> import numpy as np
>>> from bokeh.core.serialization import Serializer
>>> from bokeh.core.json_encoder import serialize_json
>>> s = Serializer()
>>> obj = dict(b=np.datetime64("2023-02-25"), a=np.arange(3))
>>> rep = s.encode(obj)
>>> rep
{
'type': 'map',
'entries': [
('b', 1677283200000.0),
('a', {
'type': 'ndarray',
'array': {'type': 'bytes', 'data': Buffer(id='p1000', data=<memory at 0x7fe5300e2d40>)},
'shape': [3],
'dtype': 'int32',
'order': 'little',
}),
],
}
>>> serialize_json(rep)
'{"type":"map","entries":[["b",1677283200000.0],["a",{"type":"ndarray","array":'
"{"type":"bytes","data":"AAAAAAEAAAACAAAA"},"shape":[3],"dtype":"int32","order":"little"}]]}'
.. note::
Using this function isn't strictly necessary. The serializer can be
configured to produce output that's fully compatible with ``dumps()``
from the standard library module ``json``. The main difference between
this function and ``dumps()`` is handling of memory buffers. Use the
following setup:
.. code-block:: python
>>> s = Serializer(deferred=False)
>>> import json
>>> json.dumps(s.encode(obj)) | def serialize_json(obj: Any | Serialized[Any], *, pretty: bool | None = None, indent: int | None = None) -> str:
'''
Convert an object or a serialized representation to a JSON string.
This function accepts Python-serializable objects and converts them to
a JSON string. This function does not perform any advaced serialization,
in particular it won't serialize Bokeh models or numpy arrays. For that,
use :class:`bokeh.core.serialization.Serializer` class, which handles
serialization of all types of objects that may be encountered in Bokeh.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Returns:
str: RFC-8259 JSON string
Examples:
.. code-block:: python
>>> import numpy as np
>>> from bokeh.core.serialization import Serializer
>>> from bokeh.core.json_encoder import serialize_json
>>> s = Serializer()
>>> obj = dict(b=np.datetime64("2023-02-25"), a=np.arange(3))
>>> rep = s.encode(obj)
>>> rep
{
'type': 'map',
'entries': [
('b', 1677283200000.0),
('a', {
'type': 'ndarray',
'array': {'type': 'bytes', 'data': Buffer(id='p1000', data=<memory at 0x7fe5300e2d40>)},
'shape': [3],
'dtype': 'int32',
'order': 'little',
}),
],
}
>>> serialize_json(rep)
'{"type":"map","entries":[["b",1677283200000.0],["a",{"type":"ndarray","array":'
"{"type":"bytes","data":"AAAAAAEAAAACAAAA"},"shape":[3],"dtype":"int32","order":"little"}]]}'
.. note::
Using this function isn't strictly necessary. The serializer can be
configured to produce output that's fully compatible with ``dumps()``
from the standard library module ``json``. The main difference between
this function and ``dumps()`` is handling of memory buffers. Use the
following setup:
.. code-block:: python
>>> s = Serializer(deferred=False)
>>> import json
>>> json.dumps(s.encode(obj))
'''
pretty = settings.pretty(pretty)
if pretty:
separators=(",", ": ")
else:
separators=(",", ":")
if pretty and indent is None:
indent = 2
content: Any
buffers: list[Buffer]
if isinstance(obj, Serialized):
content = obj.content
buffers = obj.buffers or []
else:
content = obj
buffers = []
encoder = PayloadEncoder(buffers=buffers, indent=indent, separators=separators)
return encoder.encode(content) |
Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}}) | def find(objs: Iterable[Model], selector: SelectorType) -> Iterable[Model]:
''' Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}})
'''
return (obj for obj in objs if match(obj, selector)) |
Whether a selector is a simple single field, e.g. ``{name: "foo"}``
Args:
selector (JSON-like) : query selector
field (str) : field name to check for
Returns
bool | def is_single_string_selector(selector: SelectorType, field: str) -> bool:
''' Whether a selector is a simple single field, e.g. ``{name: "foo"}``
Args:
selector (JSON-like) : query selector
field (str) : field name to check for
Returns
bool
'''
return len(selector) == 1 and field in selector and isinstance(selector[field], str) |
Test whether a given Bokeh model matches a given selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
Returns:
bool : True if the object matches, False otherwise
In general, the selectors have the form:
.. code-block:: python
{ attrname : predicate }
Where a predicate is constructed from the operators ``EQ``, ``GT``, etc.
and is used to compare against values of model attributes named
``attrname``.
For example:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(width=400)
>>> match(p, {'width': {EQ: 400}})
True
>>> match(p, {'width': {GT: 500}})
False
There are two selector keys that are handled especially. The first
is 'type', which will do an isinstance check:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> from bokeh.models import Axis
>>> p = figure()
>>> match(p.xaxis[0], {'type': Axis})
True
>>> match(p.title, {'type': Axis})
False
There is also a ``'tags'`` attribute that ``Model`` objects have, that
is a list of user-supplied values. The ``'tags'`` selector key can be
used to query against this list of tags. An object matches if any of the
tags in the selector match any of the tags on the object:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(tags = ["my plot", 10])
>>> match(p, {'tags': "my plot"})
True
>>> match(p, {'tags': ["my plot", 10]})
True
>>> match(p, {'tags': ["foo"]})
False | def match(obj: Model, selector: SelectorType) -> bool:
''' Test whether a given Bokeh model matches a given selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
Returns:
bool : True if the object matches, False otherwise
In general, the selectors have the form:
.. code-block:: python
{ attrname : predicate }
Where a predicate is constructed from the operators ``EQ``, ``GT``, etc.
and is used to compare against values of model attributes named
``attrname``.
For example:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(width=400)
>>> match(p, {'width': {EQ: 400}})
True
>>> match(p, {'width': {GT: 500}})
False
There are two selector keys that are handled especially. The first
is 'type', which will do an isinstance check:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> from bokeh.models import Axis
>>> p = figure()
>>> match(p.xaxis[0], {'type': Axis})
True
>>> match(p.title, {'type': Axis})
False
There is also a ``'tags'`` attribute that ``Model`` objects have, that
is a list of user-supplied values. The ``'tags'`` selector key can be
used to query against this list of tags. An object matches if any of the
tags in the selector match any of the tags on the object:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(tags = ["my plot", 10])
>>> match(p, {'tags': "my plot"})
True
>>> match(p, {'tags': ["my plot", 10]})
True
>>> match(p, {'tags': ["foo"]})
False
'''
for key, val in selector.items():
# test attributes
if isinstance(key, str):
# special case 'type'
if key == "type":
# type supports IN, check for that first
if isinstance(val, dict) and list(val.keys()) == [IN]:
if not any(isinstance(obj, x) for x in val[IN]): return False
# otherwise just check the type of the object against val
elif not isinstance(obj, val): return False
# special case 'tag'
elif key == 'tags':
if isinstance(val, str):
if val not in obj.tags: return False
else:
try:
if not set(val) & set(obj.tags): return False
except TypeError:
if val not in obj.tags: return False
# if the object doesn't have the attr, it doesn't match
elif not hasattr(obj, key): return False
# if the value to check is a dict, recurse
else:
attr = getattr(obj, key)
if isinstance(val, dict):
if not match(attr, val): return False
else:
if attr != val: return False
# test OR conditionals
elif key is OR:
if not _or(obj, val): return False
# test operands
elif key in _operators:
if not _operators[key](obj, val): return False
else:
raise ValueError("malformed query selector")
return True |
Get the correct Jinja2 Environment, also for frozen scripts.
| def get_env() -> Environment:
''' Get the correct Jinja2 Environment, also for frozen scripts.
'''
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader
templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates')
else:
# Non-frozen Python and cx_Freeze can use __file__ directly
templates_path = join(dirname(__file__), '_templates')
return Environment(loader=FileSystemLoader(templates_path), trim_blocks=True, lstrip_blocks=True) |
Check if property validation is currently active
Returns:
bool | def validation_on() -> bool:
""" Check if property validation is currently active
Returns:
bool
"""
return Property._should_validate |
Turn off property validation during update callbacks
Example:
.. code-block:: python
@without_property_validation
def update(attr, old, new):
# do things without validation
See Also:
:class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control | def without_property_validation(input_function):
""" Turn off property validation during update callbacks
Example:
.. code-block:: python
@without_property_validation
def update(attr, old, new):
# do things without validation
See Also:
:class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control
"""
@wraps(input_function)
def func(*args, **kwargs):
with validate(False):
return input_function(*args, **kwargs)
return func |
A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``__setitem__`` could be wrapped like this:
.. code-block:: python
# x[i] = y
@notify_owner
def __setitem__(self, i, y):
return super().__setitem__(i, y)
The returned wrapped method will have a docstring indicating what
original method it is wrapping. | def notify_owner(func):
""" A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``__setitem__`` could be wrapped like this:
.. code-block:: python
# x[i] = y
@notify_owner
def __setitem__(self, i, y):
return super().__setitem__(i, y)
The returned wrapped method will have a docstring indicating what
original method it is wrapping.
"""
def wrapper(self, *args, **kwargs):
old = self._saved_copy()
result = func(self, *args, **kwargs)
self._notify_owners(old)
return result
wrapper.__doc__ = f"Container method ``{func.__name__}`` instrumented to notify property owners"
return wrapper |
Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
is referred to when running ``check_integrity``. If a warning
is added to the silencers - then it will never be raised.
.. code-block:: python
>>> from bokeh.core.validation.warnings import EMPTY_LAYOUT
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, True)
{1002}
To turn a warning back on use the same method but with the silence
argument set to false
.. code-block:: python
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, False)
set() | def silence(warning: Warning, silence: bool = True) -> set[Warning]:
''' Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
is referred to when running ``check_integrity``. If a warning
is added to the silencers - then it will never be raised.
.. code-block:: python
>>> from bokeh.core.validation.warnings import EMPTY_LAYOUT
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, True)
{1002}
To turn a warning back on use the same method but with the silence
argument set to false
.. code-block:: python
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, False)
set()
'''
if not isinstance(warning, Warning):
raise ValueError(f"Input to silence should be a warning object - not of type {type(warning)}")
if silence:
__silencers__.add(warning)
elif warning in __silencers__:
__silencers__.remove(warning)
return __silencers__ |
Check if a warning has been silenced.
Args:
warning (Warning) : Bokeh warning to check
Returns:
bool | def is_silenced(warning: Warning) -> bool:
''' Check if a warning has been silenced.
Args:
warning (Warning) : Bokeh warning to check
Returns:
bool
'''
return warning in __silencers__ |
Collect all warnings associated with a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
ValidationIssues: A collection of all warning and error messages
This function will return an object containing all errors and/or
warning conditions that are detected. For example, layouts without
any children will add a warning to the collection:
.. code-block:: python
>>> empty_row = Row()
>>> check_integrity([empty_row])
ValidationIssues(
warning=[
ValidationIssue(
code=1002,
name="EMPTY_LAYOUT",
text="Layout has no children",
extra="Row(id='1001', ...)",
),
],
) | def check_integrity(models: Iterable[Model]) -> ValidationIssues:
''' Collect all warnings associated with a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
ValidationIssues: A collection of all warning and error messages
This function will return an object containing all errors and/or
warning conditions that are detected. For example, layouts without
any children will add a warning to the collection:
.. code-block:: python
>>> empty_row = Row()
>>> check_integrity([empty_row])
ValidationIssues(
warning=[
ValidationIssue(
code=1002,
name="EMPTY_LAYOUT",
text="Layout has no children",
extra="Row(id='1001', ...)",
),
],
)
'''
issues = ValidationIssues()
for model in models:
validators: list[Validator] = []
for name in dir(model):
if not name.startswith("_check"):
continue
obj = getattr(model, name)
if getattr(obj, "validator_type", None):
validators.append(obj)
for func in validators:
if func.validator_type == "error":
issues.error.extend(func())
else:
issues.warning.extend(func())
return issues |
Log warning and error messages for a dictionary containing warnings and error messages.
Args:
issues (ValidationIssue) : A collection of all warning and error messages
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions in the dictionary. For example, a dictionary
containing a warning for empty layout will trigger a warning:
.. code-block:: python
>>> process_validation_issues(validations)
W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...) | def process_validation_issues(issues: ValidationIssues) -> None:
''' Log warning and error messages for a dictionary containing warnings and error messages.
Args:
issues (ValidationIssue) : A collection of all warning and error messages
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions in the dictionary. For example, a dictionary
containing a warning for empty layout will trigger a warning:
.. code-block:: python
>>> process_validation_issues(validations)
W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...)
'''
errors = issues.error
warnings = [issue for issue in issues.warning if not is_silenced(Warning.get_by_code(issue.code))]
warning_messages: list[str] = []
for warning in sorted(warnings, key=lambda warning: warning.code):
msg = f"W-{warning.code} ({warning.name}): {warning.text}: {warning.extra}"
warning_messages.append(msg)
log.warning(msg)
error_messages: list[str] = []
for error in sorted(errors, key=lambda error: error.code):
msg = f"E-{error.code} ({error.name}): {error.text}: {error.extra}"
error_messages.append(msg)
log.error(msg)
if settings.validation_level() == "errors":
if len(errors):
raise RuntimeError(f"Errors encountered during validation: {error_messages}")
elif settings.validation_level() == "all":
if len(errors) or len(warnings):
raise RuntimeError(f"Errors encountered during validation: {error_messages + warning_messages}") |
Internal shared implementation to handle both error and warning
validation checks.
Args:
code code_or_name (int, str or Issue) : a defined error code or custom message
validator_type (str) : either "error" or "warning"
Returns:
validation decorator | def _validator(code_or_name: int | str | Issue, validator_type: ValidatorType) -> ValidationDecorator:
""" Internal shared implementation to handle both error and warning
validation checks.
Args:
code code_or_name (int, str or Issue) : a defined error code or custom message
validator_type (str) : either "error" or "warning"
Returns:
validation decorator
"""
issues: type[Error] | type[Warning] = \
Error if validator_type == "error" else Warning
def decorator(func: ValidationFunction) -> Validator:
assert func.__name__.startswith("_check"), f"validation function {func.__qualname__} must have '_check' prefix"
def _wrapper(*args: Any, **kwargs: Any) -> list[ValidationIssue]:
extra = func(*args, **kwargs)
if extra is None:
return []
issue: Issue
name: str
if isinstance(code_or_name, str):
issue = issues.get_by_name("EXT")
name = f"{issue.name}:{code_or_name}"
elif isinstance(code_or_name, int):
try:
issue = issues.get_by_code(code_or_name)
name = issue.name
except KeyError:
raise ValueError(f"unknown {validator_type} code {code_or_name}")
else:
issue = code_or_name
name = issue.name
code = issue.code
text = issue.description
return [ValidationIssue(code, name, text, extra)]
wrapper = cast(Validator, _wrapper)
wrapper.validator_type = validator_type
return wrapper
return decorator |
Decorator to mark a validator method for a Bokeh error condition
Args:
code_or_name (int, str or Issue) : a code from ``bokeh.validation.errors`` or a string label for a custom check
Returns:
callable : decorator for Bokeh model methods
The function that is decorated must have a name that starts with
``_check``, and return a string message in case a bad condition is
detected, and ``None`` if no bad condition is detected.
Examples:
The first example uses a numeric code for a standard error provided in
``bokeh.validation.errors``. This usage is primarily of interest to Bokeh
core developers.
.. code-block:: python
from bokeh.validation.errors import REQUIRED_RANGES
@error(REQUIRED_RANGES)
def _check_no_glyph_renderers(self):
if bad_condition: return "message"
The second example shows how a custom warning check can be implemented by
passing an arbitrary string label to the decorator. This usage is primarily
of interest to anyone extending Bokeh with their own custom models.
.. code-block:: python
@error("MY_CUSTOM_WARNING")
def _check_my_custom_warning(self):
if bad_condition: return "message" | def error(code_or_name: int | str | Issue) -> ValidationDecorator:
""" Decorator to mark a validator method for a Bokeh error condition
Args:
code_or_name (int, str or Issue) : a code from ``bokeh.validation.errors`` or a string label for a custom check
Returns:
callable : decorator for Bokeh model methods
The function that is decorated must have a name that starts with
``_check``, and return a string message in case a bad condition is
detected, and ``None`` if no bad condition is detected.
Examples:
The first example uses a numeric code for a standard error provided in
``bokeh.validation.errors``. This usage is primarily of interest to Bokeh
core developers.
.. code-block:: python
from bokeh.validation.errors import REQUIRED_RANGES
@error(REQUIRED_RANGES)
def _check_no_glyph_renderers(self):
if bad_condition: return "message"
The second example shows how a custom warning check can be implemented by
passing an arbitrary string label to the decorator. This usage is primarily
of interest to anyone extending Bokeh with their own custom models.
.. code-block:: python
@error("MY_CUSTOM_WARNING")
def _check_my_custom_warning(self):
if bad_condition: return "message"
"""
return _validator(code_or_name, "error") |
Decorator to mark a validator method for a Bokeh error condition
Args:
code_or_name (int, str or Issue) : a code from ``bokeh.validation.errors`` or a string label for a custom check
Returns:
callable : decorator for Bokeh model methods
The function that is decorated should have a name that starts with
``_check``, and return a string message in case a bad condition is
detected, and ``None`` if no bad condition is detected.
Examples:
The first example uses a numeric code for a standard warning provided in
``bokeh.validation.warnings``. This usage is primarily of interest to Bokeh
core developers.
.. code-block:: python
from bokeh.validation.warnings import MISSING_RENDERERS
@warning(MISSING_RENDERERS)
def _check_no_glyph_renderers(self):
if bad_condition: return "message"
The second example shows how a custom warning check can be implemented by
passing an arbitrary string label to the decorator. This usage is primarily
of interest to anyone extending Bokeh with their own custom models.
.. code-block:: python
@warning("MY_CUSTOM_WARNING")
def _check_my_custom_warning(self):
if bad_condition: return "message" | def warning(code_or_name: int | str | Issue) -> ValidationDecorator:
""" Decorator to mark a validator method for a Bokeh error condition
Args:
code_or_name (int, str or Issue) : a code from ``bokeh.validation.errors`` or a string label for a custom check
Returns:
callable : decorator for Bokeh model methods
The function that is decorated should have a name that starts with
``_check``, and return a string message in case a bad condition is
detected, and ``None`` if no bad condition is detected.
Examples:
The first example uses a numeric code for a standard warning provided in
``bokeh.validation.warnings``. This usage is primarily of interest to Bokeh
core developers.
.. code-block:: python
from bokeh.validation.warnings import MISSING_RENDERERS
@warning(MISSING_RENDERERS)
def _check_no_glyph_renderers(self):
if bad_condition: return "message"
The second example shows how a custom warning check can be implemented by
passing an arbitrary string label to the decorator. This usage is primarily
of interest to anyone extending Bokeh with their own custom models.
.. code-block:: python
@warning("MY_CUSTOM_WARNING")
def _check_my_custom_warning(self):
if bad_condition: return "message"
"""
return _validator(code_or_name, "warning") |
Attempt to combine a new event with a list of previous events.
The ``old_event`` will be scanned in reverse, and ``.combine(new_event)``
will be called on each. If a combination can be made, the function
will return immediately. Otherwise, ``new_event`` will be appended to
``old_events``.
Args:
new_event (DocumentChangedEvent) :
The new event to attempt to combine
old_events (list[DocumentChangedEvent])
A list of previous events to attempt to combine new_event with
**This is an "out" parameter**. The values it contains will be
modified in-place.
Returns:
None | def _combine_document_events(new_event: DocumentChangedEvent, old_events: list[DocumentChangedEvent]) -> None:
''' Attempt to combine a new event with a list of previous events.
The ``old_event`` will be scanned in reverse, and ``.combine(new_event)``
will be called on each. If a combination can be made, the function
will return immediately. Otherwise, ``new_event`` will be appended to
``old_events``.
Args:
new_event (DocumentChangedEvent) :
The new event to attempt to combine
old_events (list[DocumentChangedEvent])
A list of previous events to attempt to combine new_event with
**This is an "out" parameter**. The values it contains will be
modified in-place.
Returns:
None
'''
for event in reversed(old_events):
if event.combine(new_event):
return
# no combination was possible
old_events.append(new_event) |
Wrap a callback function to execute without first obtaining the
document lock.
Args:
func (callable) : The function to wrap
Returns:
callable : a function wrapped to execute without a |Document| lock.
While inside an unlocked callback, it is completely *unsafe* to modify
``curdoc()``. The value of ``curdoc()`` inside the callback will be a
specially wrapped version of |Document| that only allows safe operations,
which are:
* :func:`~bokeh.document.Document.add_next_tick_callback`
* :func:`~bokeh.document.Document.remove_next_tick_callback`
Only these may be used safely without taking the document lock. To make
other changes to the document, you must add a next tick callback and make
your changes to ``curdoc()`` from that second callback.
Attempts to otherwise access or change the Document will result in an
exception being raised.
``func`` can be a synchronous function, an async function, or a function
decorated with ``asyncio.coroutine``. The returned function will be an
async function if ``func`` is any of the latter two. | def without_document_lock(func: F) -> NoLockCallback[F]:
''' Wrap a callback function to execute without first obtaining the
document lock.
Args:
func (callable) : The function to wrap
Returns:
callable : a function wrapped to execute without a |Document| lock.
While inside an unlocked callback, it is completely *unsafe* to modify
``curdoc()``. The value of ``curdoc()`` inside the callback will be a
specially wrapped version of |Document| that only allows safe operations,
which are:
* :func:`~bokeh.document.Document.add_next_tick_callback`
* :func:`~bokeh.document.Document.remove_next_tick_callback`
Only these may be used safely without taking the document lock. To make
other changes to the document, you must add a next tick callback and make
your changes to ``curdoc()`` from that second callback.
Attempts to otherwise access or change the Document will result in an
exception being raised.
``func`` can be a synchronous function, an async function, or a function
decorated with ``asyncio.coroutine``. The returned function will be an
async function if ``func`` is any of the latter two.
'''
if asyncio.iscoroutinefunction(func):
@wraps(func)
async def _wrapper(*args: Any, **kw: Any) -> None:
await func(*args, **kw)
else:
@wraps(func)
def _wrapper(*args: Any, **kw: Any) -> None:
func(*args, **kw)
wrapper = cast(NoLockCallback[F], _wrapper)
wrapper.nolock = True
return wrapper |
Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[HasProps or Document]) :
resources (Resources)
Returns:
Bundle | def bundle_for_objs_and_resources(objs: Sequence[HasProps | Document] | None, resources: Resources | None) -> Bundle:
''' Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[HasProps or Document]) :
resources (Resources)
Returns:
Bundle
'''
if objs is not None:
all_objs = _all_objs(objs)
use_widgets = _use_widgets(all_objs)
use_tables = _use_tables(all_objs)
use_gl = _use_gl(all_objs)
use_mathjax = _use_mathjax(all_objs)
else:
# XXX: force all components on server and in notebook, because we don't know in advance what will be used
all_objs = None
use_widgets = True
use_tables = True
use_gl = True
use_mathjax = True
js_files: list[URL] = []
js_raw: list[str] = []
css_files: list[URL] = []
css_raw: list[str] = []
if resources is not None:
components = list(resources.components)
if not use_widgets: components.remove("bokeh-widgets")
if not use_tables: components.remove("bokeh-tables")
if not use_gl: components.remove("bokeh-gl")
if not use_mathjax: components.remove("bokeh-mathjax")
resources = resources.clone(components=components)
js_files.extend(map(URL, resources.js_files))
js_raw.extend(resources.js_raw)
css_files.extend(map(URL, resources.css_files))
css_raw.extend(resources.css_raw)
extensions = _bundle_extensions(all_objs if objs else None, resources)
mode = resources.mode
if mode == "inline":
js_raw.extend([ Resources._inline(bundle.artifact_path) for bundle in extensions ])
elif mode == "server":
js_files.extend([ bundle.server_url for bundle in extensions ])
elif mode == "cdn":
for bundle in extensions:
if bundle.cdn_url is not None:
js_files.append(bundle.cdn_url)
else:
js_raw.append(Resources._inline(bundle.artifact_path))
else:
js_files.extend([ URL(str(bundle.artifact_path)) for bundle in extensions ])
models = [ obj.__class__ for obj in all_objs ] if all_objs else None
ext = bundle_models(models)
if ext is not None:
js_raw.append(ext)
return Bundle(js_files, js_raw, css_files, css_raw, resources.hashes if resources else {}) |
Whether any of a collection of objects satisfies a given query predicate
Args:
objs (set[HasProps]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False | def _any(objs: set[HasProps], query: Callable[[HasProps], bool]) -> bool:
''' Whether any of a collection of objects satisfies a given query predicate
Args:
objs (set[HasProps]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False
'''
return any(query(x) for x in objs) |
Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[HasProps or Document]) :
Returns:
bool | def _use_tables(all_objs: set[HasProps]) -> bool:
''' Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[HasProps or Document]) :
Returns:
bool
'''
from ..models.widgets import TableWidget
return _any(all_objs, lambda obj: isinstance(obj, TableWidget)) or _ext_use_tables(all_objs) |
Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[HasProps or Document]) :
Returns:
bool | def _use_widgets(all_objs: set[HasProps]) -> bool:
''' Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[HasProps or Document]) :
Returns:
bool
'''
from ..models.widgets import Widget
return _any(all_objs, lambda obj: isinstance(obj, Widget)) or _ext_use_widgets(all_objs) |
Whether a model requires MathJax to be loaded
Args:
model (HasProps): HasProps to check
Returns:
bool: True if MathJax required, False if not | def _model_requires_mathjax(model: HasProps) -> bool:
"""Whether a model requires MathJax to be loaded
Args:
model (HasProps): HasProps to check
Returns:
bool: True if MathJax required, False if not
"""
# TODO query model's properties that include TextLike or better
# yet load mathjax bundle dynamically on bokehjs' side.
from ..models.annotations import TextAnnotation
from ..models.axes import Axis
from ..models.widgets.markups import Div, Paragraph
from ..models.widgets.sliders import AbstractSlider
if isinstance(model, TextAnnotation):
if isinstance(model.text, str) and contains_tex_string(model.text):
return True
if isinstance(model, AbstractSlider):
if isinstance(model.title, str) and contains_tex_string(model.title):
return True
if isinstance(model, Axis):
if isinstance(model.axis_label, str) and contains_tex_string(model.axis_label):
return True
for val in model.major_label_overrides.values():
if isinstance(val, str) and contains_tex_string(val):
return True
if isinstance(model, Div) and not model.disable_math and not model.render_as_text:
if contains_tex_string(model.text):
return True
if isinstance(model, Paragraph) and not model.disable_math:
if contains_tex_string(model.text):
return True
return False |
Whether a collection of Bokeh objects contains a model requesting MathJax
Args:
objs (seq[HasProps or Document]) :
Returns:
bool | def _use_mathjax(all_objs: set[HasProps]) -> bool:
''' Whether a collection of Bokeh objects contains a model requesting MathJax
Args:
objs (seq[HasProps or Document]) :
Returns:
bool
'''
from ..models.glyphs import MathTextGlyph
from ..models.text import MathText
return _any(all_objs, lambda obj: isinstance(obj, MathTextGlyph | MathText) or _model_requires_mathjax(obj)) or _ext_use_mathjax(all_objs) |
Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[HasProps or Document]) :
Returns:
bool | def _use_gl(all_objs: set[HasProps]) -> bool:
''' Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[HasProps or Document]) :
Returns:
bool
'''
from ..models.plots import Plot
return _any(all_objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl") |
Render an HTML div for a Bokeh render item.
Args:
item (RenderItem):
the item to create a div for
Returns:
str | def div_for_render_item(item: RenderItem) -> str:
''' Render an HTML div for a Bokeh render item.
Args:
item (RenderItem):
the item to create a div for
Returns:
str
'''
return PLOT_DIV.render(doc=item, macros=MACROS) |
Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
A tuple containing (bokeh_js, bokeh_css).
docs_json (JSON-like):
Serialized Bokeh Document.
render_items (RenderItems):
Specific items to render from the document and where.
title (str or None):
A title for the HTML page. If None, DEFAULT_TITLE is used.
template (str or Template or None, optional):
A Template to be used for the HTML page. If None, FILE is used.
template_variables (dict, optional):
Any Additional variables to pass to the template.
Returns:
str | def html_page_for_render_items(
bundle: Bundle | tuple[str, str],
docs_json: dict[ID, DocJson],
render_items: list[RenderItem],
title: str | None,
template: Template | str | None = None,
template_variables: dict[str, Any] = {},
) -> str:
''' Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
A tuple containing (bokeh_js, bokeh_css).
docs_json (JSON-like):
Serialized Bokeh Document.
render_items (RenderItems):
Specific items to render from the document and where.
title (str or None):
A title for the HTML page. If None, DEFAULT_TITLE is used.
template (str or Template or None, optional):
A Template to be used for the HTML page. If None, FILE is used.
template_variables (dict, optional):
Any Additional variables to pass to the template.
Returns:
str
'''
if title is None:
title = DEFAULT_TITLE
bokeh_js, bokeh_css = bundle
json_id = make_globally_unique_css_safe_id()
json = escape(serialize_json(docs_json), quote=False)
json = wrap_in_script_tag(json, "application/json", json_id)
script = wrap_in_script_tag(script_for_render_items(json_id, render_items))
context = template_variables.copy()
context.update(dict(
title = title,
bokeh_js = bokeh_js,
bokeh_css = bokeh_css,
plot_script = json + script,
docs = render_items,
base = FILE,
macros = MACROS,
))
if len(render_items) == 1:
context["doc"] = context["docs"][0]
context["roots"] = context["doc"].roots
# XXX: backwards compatibility, remove for 1.0
context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items)
if template is None:
template = FILE
elif isinstance(template, str):
template = get_env().from_string("{% extends base %}\n" + template)
html = template.render(context)
return html |
Render an script for Bokeh render items.
Args:
docs_json_or_id:
can be None
render_items (RenderItems) :
Specific items to render from the document and where
app_path (str, optional) :
absolute_url (Theme, optional) :
Returns:
str | def script_for_render_items(docs_json_or_id: ID | dict[ID, DocJson], render_items: list[RenderItem],
app_path: str | None = None, absolute_url: str | None = None) -> str:
''' Render an script for Bokeh render items.
Args:
docs_json_or_id:
can be None
render_items (RenderItems) :
Specific items to render from the document and where
app_path (str, optional) :
absolute_url (Theme, optional) :
Returns:
str
'''
if isinstance(docs_json_or_id, str):
docs_json = f"document.getElementById('{docs_json_or_id}').textContent"
else:
# XXX: encodes &, <, > and ', but not ". This is because " is used a lot in JSON,
# and encoding it would significantly increase size of generated files. Doing so
# is safe, because " in strings was already encoded by JSON, and the semi-encoded
# JSON string is included in JavaScript in single quotes.
docs_json = serialize_json(docs_json_or_id, pretty=False) # JSON string
docs_json = escape(docs_json, quote=False) # make HTML-safe
docs_json = docs_json.replace("'", "'") # remove single quotes
docs_json = docs_json.replace("\\", "\\\\") # double encode escapes
docs_json = "'" + docs_json + "'" # JS string
js = DOC_JS.render(
docs_json=docs_json,
render_items=serialize_json([ item.to_json() for item in render_items ], pretty=False),
app_path=app_path,
absolute_url=absolute_url,
)
if not settings.dev:
js = wrap_in_safely(js)
return wrap_in_onload(js) |
Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to this notebook div
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed. | def notebook_content(model: Model, notebook_comms_target: str | None = None, theme: ThemeSource = FromCurdoc) -> tuple[str, str, Document]:
''' Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to this notebook div
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed.
'''
if not isinstance(model, Model):
raise ValueError("notebook_content expects a single Model instance")
# Comms handling relies on the fact that the new_doc returned here
# has models with the same IDs as they were started with
with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc:
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
div = div_for_render_item(render_item)
render_item = render_item.to_json()
if notebook_comms_target:
render_item["notebook_comms_target"] = notebook_comms_target
script = DOC_NB_JS.render(
docs_json=serialize_json(docs_json),
render_items=serialize_json([render_item]),
)
return script, div, new_doc |
Return a script tag that embeds content from a Bokeh server.
Bokeh apps embedded using these methods will NOT set the browser window title.
Args:
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
headers (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP Headers
to Bokeh application code (default: None)
Mutually exclusive with ``with_credentials``
with_credentials (bool, optional):
Whether cookies should be passed to Bokeh application code (default: False)
Mutually exclusive with ``headers``
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server. | def server_document(url: str = "default", relative_urls: bool = False, resources: Literal["default"] | None = "default",
arguments: dict[str, str] | None = None, headers: dict[str, str] | None = None, with_credentials: bool = False) -> str:
''' Return a script tag that embeds content from a Bokeh server.
Bokeh apps embedded using these methods will NOT set the browser window title.
Args:
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
headers (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP Headers
to Bokeh application code (default: None)
Mutually exclusive with ``with_credentials``
with_credentials (bool, optional):
Whether cookies should be passed to Bokeh application code (default: False)
Mutually exclusive with ``headers``
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
'''
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_globally_unique_css_safe_id()
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_resources(resources)
src_path += _process_arguments(arguments)
if headers and with_credentials:
raise ValueError("'headers' and 'with_credentials' are mutually exclusive")
elif not headers:
headers = {}
tag = AUTOLOAD_REQUEST_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
headers = headers,
with_credentials = with_credentials,
)
return tag |
Return a script tag that embeds content from a specific existing session on
a Bokeh server.
This function is typically only useful for serving from a a specific session
that was previously created using the ``bokeh.client`` API.
Bokeh apps embedded using these methods will NOT set the browser window title.
.. note::
Typically you will not want to save or re-use the output of this
function for different or multiple page loads.
Args:
model (Model or None, optional) :
The object to render from the session, or None. (default: None)
If None, the entire document will be rendered.
session_id (str) :
A server session ID
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
headers (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP Headers
to Bokeh application code (default: None)
Mutually exclusive with ``with_credentials``
with_credentials (bool, optional):
Whether cookies should be passed to Bokeh application code (default: False)
Mutually exclusive with ``headers``
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
.. warning::
It is typically a bad idea to re-use the same ``session_id`` for
every page load. This is likely to create scalability and security
problems, and will cause "shared Google doc" behavior, which is
probably not desired. | def server_session(model: Model | None = None, session_id: ID | None = None, url: str = "default",
relative_urls: bool = False, resources: Literal["default"] | None = "default", headers: dict[str, str] = {},
with_credentials: bool = False) -> str:
''' Return a script tag that embeds content from a specific existing session on
a Bokeh server.
This function is typically only useful for serving from a a specific session
that was previously created using the ``bokeh.client`` API.
Bokeh apps embedded using these methods will NOT set the browser window title.
.. note::
Typically you will not want to save or re-use the output of this
function for different or multiple page loads.
Args:
model (Model or None, optional) :
The object to render from the session, or None. (default: None)
If None, the entire document will be rendered.
session_id (str) :
A server session ID
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
headers (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP Headers
to Bokeh application code (default: None)
Mutually exclusive with ``with_credentials``
with_credentials (bool, optional):
Whether cookies should be passed to Bokeh application code (default: False)
Mutually exclusive with ``headers``
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
.. warning::
It is typically a bad idea to re-use the same ``session_id`` for
every page load. This is likely to create scalability and security
problems, and will cause "shared Google doc" behavior, which is
probably not desired.
'''
if session_id is None:
raise ValueError("Must supply a session_id")
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_globally_unique_css_safe_id()
modelid = "" if model is None else model.id
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_resources(resources)
if headers and with_credentials:
raise ValueError("'headers' and 'with_credentials' are mutually exclusive")
elif not headers:
headers = {}
else:
headers = dict(headers)
headers['Bokeh-Session-Id'] = session_id
tag = AUTOLOAD_REQUEST_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
modelid = modelid,
headers = headers,
with_credentials = with_credentials,
)
return tag |
Args:
session (ServerSession) :
resources (Resources) :
title (str) :
template (Template) :
template_variables (dict) :
Returns:
str | def server_html_page_for_session(session: ServerSession, resources: Resources, title: str,
template: Template = FILE, template_variables: dict[str, Any] | None = None):
'''
Args:
session (ServerSession) :
resources (Resources) :
title (str) :
template (Template) :
template_variables (dict) :
Returns:
str
'''
render_item = RenderItem(
token = session.token,
roots = session.document.roots,
use_for_title = True,
)
if template_variables is None:
template_variables = {}
bundle = bundle_for_objs_and_resources(None, resources)
html = html_page_for_render_items(bundle, {}, [render_item], title,
template=template, template_variables=template_variables)
return html |
Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str | def _clean_url(url: str) -> str:
''' Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str
'''
if url == 'default':
url = DEFAULT_SERVER_HTTP_URL
if url.startswith("ws"):
raise ValueError("url should be the http or https URL for the server, not the websocket URL")
return url.rstrip("/") |
Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str | def _get_app_path(url: str) -> str:
''' Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str
'''
app_path = urlparse(url).path.rstrip("/")
if not app_path.startswith("/"):
app_path = "/" + app_path
return app_path |
Return user-supplied HTML arguments to add to a Bokeh server URL.
Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL
Returns:
str | def _process_arguments(arguments: dict[str, str] | None) -> str:
''' Return user-supplied HTML arguments to add to a Bokeh server URL.
Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL
Returns:
str
'''
if arguments is None:
return ""
result = ""
for key, value in arguments.items():
if not key.startswith("bokeh-"):
result += f"&{quote_plus(str(key))}={quote_plus(str(value))}"
return result |
Return an app path HTML argument to add to a Bokeh server URL.
Args:
app_path (str) :
The app path to add. If the app path is ``/`` then it will be
ignored and an empty string returned. | def _process_app_path(app_path: str) -> str:
''' Return an app path HTML argument to add to a Bokeh server URL.
Args:
app_path (str) :
The app path to add. If the app path is ``/`` then it will be
ignored and an empty string returned.
'''
if app_path == "/": return ""
return "&bokeh-app-path=" + app_path |
Return an absolute URL HTML argument to add to a Bokeh server URL, if
requested.
Args:
relative_urls (book) :
If false, generate an absolute URL to add.
url (str) :
The absolute URL to add as an HTML argument
Returns:
str | def _process_relative_urls(relative_urls: bool, url: str) -> str:
''' Return an absolute URL HTML argument to add to a Bokeh server URL, if
requested.
Args:
relative_urls (book) :
If false, generate an absolute URL to add.
url (str) :
The absolute URL to add as an HTML argument
Returns:
str
'''
if relative_urls: return ""
return "&bokeh-absolute-url=" + url |
Return an argument to suppress normal Bokeh server resources, if requested.
Args:
resources ("default" or None) :
If None, return an HTML argument to suppress default resources.
Returns:
str | def _process_resources(resources: Literal["default"] | None) -> str:
''' Return an argument to suppress normal Bokeh server resources, if requested.
Args:
resources ("default" or None) :
If None, return an HTML argument to suppress default resources.
Returns:
str
'''
if resources not in ("default", None):
raise ValueError("`resources` must be either 'default' or None.")
if resources is None:
return "&resources=none"
return "" |
Return a base autoload URL for a given element ID
Args:
url (str) :
The base server URL
elementid (str) :
The div ID for autload to target
Returns:
str | def _src_path(url: str, elementid: ID) -> str:
''' Return a base autoload URL for a given element ID
Args:
url (str) :
The base server URL
elementid (str) :
The div ID for autload to target
Returns:
str
'''
return url + "/autoload.js?bokeh-autoload-element=" + elementid |
Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
JavaScript code to be saved at ``script_path`` and a ``<script>``
tag to load it
Raises:
ValueError | def autoload_static(model: Model | Document, resources: Resources, script_path: str) -> tuple[str, str]:
''' Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
JavaScript code to be saved at ``script_path`` and a ``<script>``
tag to load it
Raises:
ValueError
'''
# TODO: maybe warn that it's not exactly useful, but technically possible
# if resources.mode == 'inline':
# raise ValueError("autoload_static() requires non-inline resources")
if isinstance(model, Model):
models = [model]
elif isinstance (model, Document):
models = model.roots
else:
raise ValueError("autoload_static expects a single Model or Document")
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
bundle = bundle_for_objs_and_resources(None, resources)
bundle.add(Script(script_for_render_items(docs_json, [render_item])))
(_, elementid) = next(iter(render_item.roots.to_json().items()))
js = wrap_in_onload(AUTOLOAD_JS.render(bundle=bundle, elementid=elementid))
tag = AUTOLOAD_TAG.render(
src_path = script_path,
elementid = elementid,
)
return js, tag |
Return HTML components to embed a Bokeh plot. The data for the plot is
stored directly in the returned HTML.
An example can be found in examples/embed/embed_multiple.py
The returned components assume that BokehJS resources are **already loaded**.
The HTML document or template in which they will be embedded needs to
include scripts tags, either from a local URL or Bokeh's CDN (replacing
``x.y.z`` with the version of Bokeh you are using):
.. code-block:: html
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-x.y.z.min.js"></script>
Only the Bokeh core library ``bokeh-x.y.z.min.js`` is always required. The
other scripts are optional and only need to be included if you want to use
corresponding features:
* The ``"bokeh-widgets"`` files are only necessary if you are using any of the
:ref:`Bokeh widgets <ug_interaction_widgets>`.
* The ``"bokeh-tables"`` files are only necessary if you are using Bokeh's
:ref:`data tables <ug_interaction_widgets_examples_datatable>`.
* The ``"bokeh-api"`` files are required to use the
:ref:`BokehJS API <ug_advanced_bokehjs>` and must be loaded *after* the
core BokehJS library.
* The ``"bokeh-gl"`` files are required to enable
:ref:`WebGL support <ug_output_webgl>`.
* the ``"bokeh-mathjax"`` files are required to enable
:ref:`MathJax support <ug_styling_mathtext>`.
Args:
models (Model|list|dict|tuple) :
A single Model, a list/tuple of Models, or a dictionary of keys
and Models.
wrap_script (boolean, optional) :
If True, the returned javascript is wrapped in a script tag.
(default: True)
wrap_plot_info (boolean, optional) :
If True, returns ``<div>`` strings. Otherwise, return
:class:`~bokeh.embed.RenderRoot` objects that can be used to build
your own divs. (default: True)
theme (Theme, optional) :
Applies the specified theme when creating the components. If None,
or not specified, and the supplied models constitute the full set
of roots of a document, applies the theme of that document to the
components. Otherwise applies the default theme.
Returns:
UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])*
Examples:
With default wrapping parameter values:
.. code-block:: python
components(plot)
# => (script, plot_div)
components((plot1, plot2))
# => (script, (plot1_div, plot2_div))
components({"Plot 1": plot1, "Plot 2": plot2})
# => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div})
Examples:
With wrapping parameters set to ``False``:
.. code-block:: python
components(plot, wrap_script=False, wrap_plot_info=False)
# => (javascript, plot_root)
components((plot1, plot2), wrap_script=False, wrap_plot_info=False)
# => (javascript, (plot1_root, plot2_root))
components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False)
# => (javascript, {"Plot 1": plot1_root, "Plot 2": plot2_root}) | def components(models: Model | Sequence[Model] | dict[str, Model], wrap_script: bool = True,
wrap_plot_info: bool = True, theme: ThemeLike = None) -> tuple[str, Any]:
''' Return HTML components to embed a Bokeh plot. The data for the plot is
stored directly in the returned HTML.
An example can be found in examples/embed/embed_multiple.py
The returned components assume that BokehJS resources are **already loaded**.
The HTML document or template in which they will be embedded needs to
include scripts tags, either from a local URL or Bokeh's CDN (replacing
``x.y.z`` with the version of Bokeh you are using):
.. code-block:: html
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-x.y.z.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-x.y.z.min.js"></script>
Only the Bokeh core library ``bokeh-x.y.z.min.js`` is always required. The
other scripts are optional and only need to be included if you want to use
corresponding features:
* The ``"bokeh-widgets"`` files are only necessary if you are using any of the
:ref:`Bokeh widgets <ug_interaction_widgets>`.
* The ``"bokeh-tables"`` files are only necessary if you are using Bokeh's
:ref:`data tables <ug_interaction_widgets_examples_datatable>`.
* The ``"bokeh-api"`` files are required to use the
:ref:`BokehJS API <ug_advanced_bokehjs>` and must be loaded *after* the
core BokehJS library.
* The ``"bokeh-gl"`` files are required to enable
:ref:`WebGL support <ug_output_webgl>`.
* the ``"bokeh-mathjax"`` files are required to enable
:ref:`MathJax support <ug_styling_mathtext>`.
Args:
models (Model|list|dict|tuple) :
A single Model, a list/tuple of Models, or a dictionary of keys
and Models.
wrap_script (boolean, optional) :
If True, the returned javascript is wrapped in a script tag.
(default: True)
wrap_plot_info (boolean, optional) :
If True, returns ``<div>`` strings. Otherwise, return
:class:`~bokeh.embed.RenderRoot` objects that can be used to build
your own divs. (default: True)
theme (Theme, optional) :
Applies the specified theme when creating the components. If None,
or not specified, and the supplied models constitute the full set
of roots of a document, applies the theme of that document to the
components. Otherwise applies the default theme.
Returns:
UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])*
Examples:
With default wrapping parameter values:
.. code-block:: python
components(plot)
# => (script, plot_div)
components((plot1, plot2))
# => (script, (plot1_div, plot2_div))
components({"Plot 1": plot1, "Plot 2": plot2})
# => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div})
Examples:
With wrapping parameters set to ``False``:
.. code-block:: python
components(plot, wrap_script=False, wrap_plot_info=False)
# => (javascript, plot_root)
components((plot1, plot2), wrap_script=False, wrap_plot_info=False)
# => (javascript, (plot1_root, plot2_root))
components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False)
# => (javascript, {"Plot 1": plot1_root, "Plot 2": plot2_root})
'''
# 1) Convert single items and dicts into list
# XXX: was_single_object = isinstance(models, Model) #or isinstance(models, Document)
was_single_object = False
if isinstance(models, Model):
was_single_object = True
models = [models]
models = _check_models_or_docs(models) # type: ignore # XXX: this API needs to be refined
# now convert dict to list, saving keys in the same order
model_keys = None
dict_type: type[dict[Any, Any]] = dict
if isinstance(models, dict):
dict_type = models.__class__
model_keys = models.keys()
models = list(models.values())
# 2) Append models to one document. Either pre-existing or new and render
with OutputDocumentFor(models, apply_theme=theme):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
bundle = bundle_for_objs_and_resources(None, None)
bundle.add(Script(script_for_render_items(docs_json, [render_item])))
script = bundle.scripts(tag=wrap_script)
def div_for_root(root: RenderRoot) -> str:
return ROOT_DIV.render(root=root, macros=MACROS)
results: list[str] | list[RenderRoot]
if wrap_plot_info:
results = [div_for_root(root) for root in render_item.roots]
else:
results = list(render_item.roots)
# 3) convert back to the input shape
result: Any
if was_single_object:
result = results[0]
elif model_keys is not None:
result = dict_type(zip(model_keys, results))
else:
result = tuple(results)
return script, result |
Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object or objects to render
typically a Model or Document
resources (ResourcesLike) :
A resources configuration for Bokeh JS & CSS assets.
title (str, optional) :
A title for the HTML document ``<title>`` tags or None. (default: None)
If None, attempt to automatically find the Document title from the given
plot objects.
template (Template, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required
template parameters
template_variables (dict, optional) : variables to be used in the Jinja2
template. If used, the following variable names will be overwritten:
title, bokeh_js, bokeh_css, plot_script, plot_div
theme (Theme, optional) :
Applies the specified theme to the created html. If ``None``, or
not specified, and the function is passed a document or the full set
of roots of a document, applies the theme of that document. Otherwise
applies the default theme.
suppress_callback_warning (bool, optional) :
Normally generating standalone HTML from a Bokeh Document that has
Python callbacks will result in a warning stating that the callbacks
cannot function. However, this warning can be suppressed by setting
this value to True (default: False)
Returns:
UTF-8 encoded HTML | def file_html(models: Model | Document | Sequence[Model],
resources: ResourcesLike | None = None,
title: str | None = None,
*,
template: Template | str = FILE,
template_variables: dict[str, Any] = {},
theme: ThemeLike = None,
suppress_callback_warning: bool = False,
_always_new: bool = False) -> str:
''' Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object or objects to render
typically a Model or Document
resources (ResourcesLike) :
A resources configuration for Bokeh JS & CSS assets.
title (str, optional) :
A title for the HTML document ``<title>`` tags or None. (default: None)
If None, attempt to automatically find the Document title from the given
plot objects.
template (Template, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required
template parameters
template_variables (dict, optional) : variables to be used in the Jinja2
template. If used, the following variable names will be overwritten:
title, bokeh_js, bokeh_css, plot_script, plot_div
theme (Theme, optional) :
Applies the specified theme to the created html. If ``None``, or
not specified, and the function is passed a document or the full set
of roots of a document, applies the theme of that document. Otherwise
applies the default theme.
suppress_callback_warning (bool, optional) :
Normally generating standalone HTML from a Bokeh Document that has
Python callbacks will result in a warning stating that the callbacks
cannot function. However, this warning can be suppressed by setting
this value to True (default: False)
Returns:
UTF-8 encoded HTML
'''
models_seq: Sequence[Model] = []
if isinstance(models, Model):
models_seq = [models]
elif isinstance(models, Document):
if len(models.roots) == 0:
raise ValueError("Document has no root Models")
models_seq = models.roots
else:
models_seq = models
resources = Resources.build(resources)
with OutputDocumentFor(models_seq, apply_theme=theme, always_new=_always_new) as doc:
(docs_json, render_items) = standalone_docs_json_and_render_items(models_seq, suppress_callback_warning=suppress_callback_warning)
title = _title_from_models(models_seq, title)
bundle = bundle_for_objs_and_resources([doc], resources)
return html_page_for_render_items(bundle, docs_json, render_items, title=title,
template=template, template_variables=template_variables) |
Return a JSON block that can be used to embed standalone Bokeh content.
Args:
model (Model) :
The Bokeh object to embed
target (string, optional)
A div id to embed the model into. If None, the target id must
be supplied in the JavaScript call.
theme (Theme, optional) :
Applies the specified theme to the created html. If ``None``, or
not specified, and the function is passed a document or the full set
of roots of a document, applies the theme of that document. Otherwise
applies the default theme.
Returns:
JSON-like
This function returns a JSON block that can be consumed by the BokehJS
function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for
``/plot`` might return the following content to embed a Bokeh plot into
a div with id *"myplot"*:
.. code-block:: python
@app.route('/plot')
def plot():
p = make_plot('petal_width', 'petal_length')
return json.dumps(json_item(p, "myplot"))
Then a web page can retrieve this JSON and embed the plot by calling
``Bokeh.embed.embed_item``:
.. code-block:: html
<script>
fetch('/plot')
.then(function(response) { return response.json(); })
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Alternatively, if is more convenient to supply the target div id directly
in the page source, that is also possible. If `target_id` is omitted in the
call to this function:
.. code-block:: python
return json.dumps(json_item(p))
Then the value passed to ``embed_item`` is used:
.. code-block:: javascript
Bokeh.embed.embed_item(item, "myplot"); | def json_item(model: Model, target: ID | None = None, theme: ThemeLike = None) -> StandaloneEmbedJson:
''' Return a JSON block that can be used to embed standalone Bokeh content.
Args:
model (Model) :
The Bokeh object to embed
target (string, optional)
A div id to embed the model into. If None, the target id must
be supplied in the JavaScript call.
theme (Theme, optional) :
Applies the specified theme to the created html. If ``None``, or
not specified, and the function is passed a document or the full set
of roots of a document, applies the theme of that document. Otherwise
applies the default theme.
Returns:
JSON-like
This function returns a JSON block that can be consumed by the BokehJS
function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for
``/plot`` might return the following content to embed a Bokeh plot into
a div with id *"myplot"*:
.. code-block:: python
@app.route('/plot')
def plot():
p = make_plot('petal_width', 'petal_length')
return json.dumps(json_item(p, "myplot"))
Then a web page can retrieve this JSON and embed the plot by calling
``Bokeh.embed.embed_item``:
.. code-block:: html
<script>
fetch('/plot')
.then(function(response) { return response.json(); })
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Alternatively, if is more convenient to supply the target div id directly
in the page source, that is also possible. If `target_id` is omitted in the
call to this function:
.. code-block:: python
return json.dumps(json_item(p))
Then the value passed to ``embed_item`` is used:
.. code-block:: javascript
Bokeh.embed.embed_item(item, "myplot");
'''
with OutputDocumentFor([model], apply_theme=theme) as doc:
doc.title = ""
[doc_json] = standalone_docs_json([model]).values()
root_id = doc_json["roots"][0]["id"]
return StandaloneEmbedJson(
target_id = target,
root_id = root_id,
doc = doc_json,
version = __version__,
) |
def _check_models_or_docs(models: ModelLike | ModelLikeCollection) -> ModelLikeCollection:
'''
'''
input_type_valid = False
# Check for single item
if isinstance(models, Model | Document):
models = [models]
# Check for sequence
if isinstance(models, Sequence) and all(isinstance(x, Model | Document) for x in models):
input_type_valid = True
if isinstance(models, dict) and \
all(isinstance(x, str) for x in models.keys()) and \
all(isinstance(x, Model | Document) for x in models.values()):
input_type_valid = True
if not input_type_valid:
raise ValueError(
'Input must be a Model, a Document, a Sequence of Models and Document, or a dictionary from string to Model and Document',
)
return models |
|
Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the models will be considered to be part of a single
Document, with any theme specified, which can thus be serialized as a unit. Where
possible, OutputDocumentFor attempts to use an existing Document. However, this is
not possible in three cases:
* If passed a series of models that have no Document at all, a new Document will
be created, and all the models will be added as roots. After the context manager
exits, the new Document will continue to be the models' document.
* If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes"
the models in a new bare Document that is only available inside the context manager.
* If passed a list of models that have different documents, then OutputDocumentFor
temporarily "re-homes" the models in a new bare Document that is only available
inside the context manager.
OutputDocumentFor will also perfom document validation before yielding, if
``settings.perform_document_validation()`` is True.
objs (seq[Model]) :
a sequence of Models that will be serialized, and need a common document
apply_theme (Theme or FromCurdoc or None, optional):
Sets the theme for the doc while inside this context manager. (default: None)
If None, use whatever theme is on the document that is found or created
If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards
If a Theme instance, use that theme, restoring any previous theme afterwards
always_new (bool, optional) :
Always return a new document, even in cases where it is otherwise possible
to use an existing document on models.
Yields:
Document | def OutputDocumentFor(objs: Sequence[Model], apply_theme: Theme | type[FromCurdoc] | None = None,
always_new: bool = False) -> Iterator[Document]:
''' Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the models will be considered to be part of a single
Document, with any theme specified, which can thus be serialized as a unit. Where
possible, OutputDocumentFor attempts to use an existing Document. However, this is
not possible in three cases:
* If passed a series of models that have no Document at all, a new Document will
be created, and all the models will be added as roots. After the context manager
exits, the new Document will continue to be the models' document.
* If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes"
the models in a new bare Document that is only available inside the context manager.
* If passed a list of models that have different documents, then OutputDocumentFor
temporarily "re-homes" the models in a new bare Document that is only available
inside the context manager.
OutputDocumentFor will also perfom document validation before yielding, if
``settings.perform_document_validation()`` is True.
objs (seq[Model]) :
a sequence of Models that will be serialized, and need a common document
apply_theme (Theme or FromCurdoc or None, optional):
Sets the theme for the doc while inside this context manager. (default: None)
If None, use whatever theme is on the document that is found or created
If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards
If a Theme instance, use that theme, restoring any previous theme afterwards
always_new (bool, optional) :
Always return a new document, even in cases where it is otherwise possible
to use an existing document on models.
Yields:
Document
'''
# Note: Comms handling relies on the fact that the new_doc returned
# has models with the same IDs as they were started with
if not isinstance(objs, Sequence) or len(objs) == 0 or not all(isinstance(x, Model) for x in objs):
raise ValueError("OutputDocumentFor expects a non-empty sequence of Models")
def finish() -> None:
pass
docs = {obj.document for obj in objs if obj.document is not None}
if always_new:
def finish() -> None:
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
else:
if len(docs) == 0:
doc = _new_doc()
for model in objs:
doc.add_root(model)
# handle a single shared document
elif len(docs) == 1:
doc = docs.pop()
# we are not using all the roots, make a quick clone for outputting purposes
if set(objs) != set(doc.roots):
def finish() -> None:
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
# we are using all the roots of a single doc, just use doc as-is
pass # lgtm [py/unnecessary-pass]
# models have mixed docs, just make a quick clone
else:
def finish():
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
if settings.perform_document_validation():
doc.validate()
_set_temp_theme(doc, apply_theme)
yield doc
_unset_temp_theme(doc)
finish() |
def standalone_docs_json(models: Sequence[Model | Document]) -> dict[ID, DocJson]:
'''
'''
docs_json, _ = standalone_docs_json_and_render_items(models)
return docs_json |
|
def standalone_docs_json_and_render_items(models: Model | Document | Sequence[Model | Document], *,
suppress_callback_warning: bool = False) -> tuple[dict[ID, DocJson], list[RenderItem]]:
'''
'''
if isinstance(models, Model | Document):
models = [models]
if not (isinstance(models, Sequence) and all(isinstance(x, Model | Document) for x in models)):
raise ValueError("Expected a Model, Document, or Sequence of Models or Documents")
if submodel_has_python_callbacks(models) and not suppress_callback_warning:
log.warning(_CALLBACKS_WARNING)
docs: dict[Document, tuple[ID, dict[Model, ID]]] = {}
for model_or_doc in models:
if isinstance(model_or_doc, Document):
model = None
doc = model_or_doc
else:
model = model_or_doc
doc = model.document
if doc is None:
raise ValueError("A Bokeh Model must be part of a Document to render as standalone content")
if doc not in docs:
docs[doc] = (make_globally_unique_id(), dict())
(docid, roots) = docs[doc]
if model is not None:
roots[model] = make_globally_unique_css_safe_id()
else:
for model in doc.roots:
roots[model] = make_globally_unique_css_safe_id()
docs_json: dict[ID, DocJson] = {}
for doc, (docid, _) in docs.items():
docs_json[docid] = doc.to_json(deferred=False)
render_items: list[RenderItem] = []
for _, (docid, roots) in docs.items():
render_items.append(RenderItem(docid, roots=roots))
return (docs_json, render_items) |
|
Traverses submodels to check for Python (event) callbacks
| def submodel_has_python_callbacks(models: Sequence[Model | Document]) -> bool:
''' Traverses submodels to check for Python (event) callbacks
'''
has_python_callback = False
for model in collect_models(models):
if len(model._callbacks) > 0 or len(model._event_callbacks) > 0:
has_python_callback = True
break
return has_python_callback |
Whether a string begins and ends with MathJax default delimiters
Args:
text (str): String to check
Returns:
bool: True if string begins and ends with delimiters, False if not | def is_tex_string(text: str) -> bool:
''' Whether a string begins and ends with MathJax default delimiters
Args:
text (str): String to check
Returns:
bool: True if string begins and ends with delimiters, False if not
'''
dollars = r"^\$\$.*?\$\$$"
braces = r"^\\\[.*?\\\]$"
parens = r"^\\\(.*?\\\)$"
pat = re.compile(f"{dollars}|{braces}|{parens}", flags=re.S)
return pat.match(text) is not None |
Whether a string contains any pair of MathJax default delimiters
Args:
text (str): String to check
Returns:
bool: True if string contains delimiters, False if not | def contains_tex_string(text: str) -> bool:
''' Whether a string contains any pair of MathJax default delimiters
Args:
text (str): String to check
Returns:
bool: True if string contains delimiters, False if not
'''
# these are non-greedy
dollars = r"\$\$.*?\$\$"
braces = r"\\\[.*?\\\]"
parens = r"\\\(.*?\\\)"
pat = re.compile(f"{dollars}|{braces}|{parens}", flags=re.S)
return pat.search(text) is not None |
def wrap_in_onload(code: str) -> str:
'''
'''
return _ONLOAD % dict(code=indent(code, 4)) |
|
def wrap_in_safely(code: str) -> str:
'''
'''
return _SAFELY % dict(code=indent(code, 2)) |
|
def wrap_in_script_tag(js: str, type: str="text/javascript", id: str | None = None) -> str:
'''
'''
return SCRIPT_TAG.render(js_code=indent(js, 2), type=type, id=id) |
|
Return the document for the current default state.
Returns:
Document : the current default document object. | def curdoc() -> Document:
''' Return the document for the current default state.
Returns:
Document : the current default document object.
'''
if len(_PATCHED_CURDOCS) > 0:
doc = _PATCHED_CURDOCS[-1]()
if doc is None:
raise RuntimeError("Patched curdoc has been previously destroyed")
return cast(Document, doc) # UnlockedDocumentProxy -> Document
return curstate().document |
Temporarily override the value of ``curdoc()`` and then return it to
its original state.
This context manager is useful for controlling the value of ``curdoc()``
while invoking functions (e.g. callbacks). The cont
Args:
doc (Document) : new Document to use for ``curdoc()`` | def patch_curdoc(doc: Document | UnlockedDocumentProxy) -> Iterator[None]:
''' Temporarily override the value of ``curdoc()`` and then return it to
its original state.
This context manager is useful for controlling the value of ``curdoc()``
while invoking functions (e.g. callbacks). The cont
Args:
doc (Document) : new Document to use for ``curdoc()``
'''
global _PATCHED_CURDOCS
_PATCHED_CURDOCS.append(weakref.ref(doc))
del doc
yield
_PATCHED_CURDOCS.pop() |
Configure the current document (returned by curdoc()).
Args:
doc (Document) : new Document to use for curdoc()
Returns:
None
.. warning::
Calling this function will replace any existing document. | def set_curdoc(doc: Document) -> None:
''' Configure the current document (returned by curdoc()).
Args:
doc (Document) : new Document to use for curdoc()
Returns:
None
.. warning::
Calling this function will replace any existing document.
'''
curstate().document = doc |
Export the ``UIElement`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (UIElement or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
scale_factor (float, optional) : A factor to scale the output PNG by,
providing a higher resolution while maintaining element relative
scales.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filename (str) : the filename where the static file is saved.
If you would like to access an Image object directly, rather than save a
file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png`
function.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | def export_png(obj: UIElement | Document, *, filename: PathLike | None = None, width: int | None = None,
height: int | None = None, scale_factor: float = 1, webdriver: WebDriver | None = None,
timeout: int = 5, state: State | None = None) -> str:
''' Export the ``UIElement`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (UIElement or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
scale_factor (float, optional) : A factor to scale the output PNG by,
providing a higher resolution while maintaining element relative
scales.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filename (str) : the filename where the static file is saved.
If you would like to access an Image object directly, rather than save a
file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png`
function.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
image = get_screenshot_as_png(obj, width=width, height=height, scale_factor=scale_factor, driver=webdriver,
timeout=timeout, state=state)
if filename is None:
filename = default_filename("png")
if image.width == 0 or image.height == 0:
raise ValueError("unable to save an empty image")
filename = os.fspath(filename) # XXX: Image.save() doesn't fully support PathLike
image.save(filename)
return abspath(expanduser(filename)) |
Export a layout as SVG file or a document as a set of SVG files.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5)
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | def export_svg(obj: UIElement | Document, *, filename: PathLike | None = None, width: int | None = None,
height: int | None = None, webdriver: WebDriver | None = None, timeout: int = 5, state: State | None = None) -> list[str]:
''' Export a layout as SVG file or a document as a set of SVG files.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5)
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
svgs = get_svg(obj, width=width, height=height, driver=webdriver, timeout=timeout, state=state)
return _write_collection(svgs, filename, "svg") |
Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (str, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | def export_svgs(obj: UIElement | Document, *, filename: str | None = None, width: int | None = None,
height: int | None = None, webdriver: WebDriver | None = None, timeout: int = 5, state: State | None = None) -> list[str]:
''' Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (str, optional) : filename to save document under (default: None)
If None, infer from the filename.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
svgs = get_svgs(obj, width=width, height=height, driver=webdriver, timeout=timeout, state=state)
if len(svgs) == 0:
log.warning("No SVG Plots were found.")
return []
return _write_collection(svgs, filename, "svg") |
Get a screenshot of a ``UIElement`` object.
Args:
obj (UIElement or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time to wait for initialization.
It will be used as a timeout for loading Bokeh, then when waiting for
the layout to be rendered.
scale_factor (float, optional) : A factor to scale the output PNG by,
providing a higher resolution while maintaining element relative
scales.
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
image (PIL.Image.Image) : a pillow image loaded from PNG.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | def get_screenshot_as_png(obj: UIElement | Document, *, driver: WebDriver | None = None, timeout: int = 5,
resources: Resources = INLINE, width: int | None = None, height: int | None = None,
scale_factor: float = 1, state: State | None = None) -> Image.Image:
''' Get a screenshot of a ``UIElement`` object.
Args:
obj (UIElement or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time to wait for initialization.
It will be used as a timeout for loading Bokeh, then when waiting for
the layout to be rendered.
scale_factor (float, optional) : A factor to scale the output PNG by,
providing a higher resolution while maintaining element relative
scales.
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
image (PIL.Image.Image) : a pillow image loaded from PNG.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
from .webdriver import (
get_web_driver_device_pixel_ratio,
scale_factor_less_than_web_driver_device_pixel_ratio,
webdriver_control,
)
with _tmp_html() as tmp:
theme = (state or curstate()).document.theme
html = get_layout_html(obj, resources=resources, width=width, height=height, theme=theme)
with open(tmp.path, mode="w", encoding="utf-8") as file:
file.write(html)
if driver is not None:
web_driver = driver
if not scale_factor_less_than_web_driver_device_pixel_ratio(scale_factor, web_driver):
device_pixel_ratio = get_web_driver_device_pixel_ratio(web_driver)
raise ValueError(f'Expected the web driver to have a device pixel ratio greater than {scale_factor}. '
f'Was given a web driver with a device pixel ratio of {device_pixel_ratio}.')
else:
web_driver = webdriver_control.get(scale_factor=scale_factor)
web_driver.maximize_window()
web_driver.get(f"file://{tmp.path}")
wait_until_render_complete(web_driver, timeout)
[width, height, dpr] = _maximize_viewport(web_driver)
png = web_driver.get_screenshot_as_png()
from PIL import Image
return (Image.open(io.BytesIO(png))
.convert("RGBA")
.crop((0, 0, width*dpr, height*dpr))
.resize((int(width*scale_factor), int(height*scale_factor)))) |
def get_layout_html(obj: UIElement | Document, *, resources: Resources = INLINE,
width: int | None = None, height: int | None = None, theme: Theme | None = None) -> str:
'''
'''
template = r"""\
{% block preamble %}
<style>
html, body {
box-sizing: border-box;
width: 100%;
height: 100%;
margin: 0;
border: 0;
padding: 0;
overflow: hidden;
}
</style>
{% endblock %}
"""
def html() -> str:
return file_html(
obj,
resources=resources,
title="",
template=template,
theme=theme,
suppress_callback_warning=True,
_always_new=True,
)
if width is not None or height is not None:
# Defer this import, it is expensive
from ..models.plots import Plot
if not isinstance(obj, Plot):
warn("Export method called with width or height argument on a non-Plot model. The size values will be ignored.")
else:
with _resized(obj, width, height):
return html()
return html() |
|
def wait_until_render_complete(driver: WebDriver, timeout: int) -> None:
'''
'''
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
def is_bokeh_loaded(driver: WebDriver) -> bool:
return cast(bool, driver.execute_script('''
return typeof Bokeh !== "undefined" && Bokeh.documents != null && Bokeh.documents.length != 0
'''))
try:
WebDriverWait(driver, timeout, poll_frequency=0.1).until(is_bokeh_loaded)
except TimeoutException as e:
_log_console(driver)
raise RuntimeError('Bokeh was not loaded in time. Something may have gone wrong.') from e
driver.execute_script(_WAIT_SCRIPT)
def is_bokeh_render_complete(driver: WebDriver) -> bool:
return cast(bool, driver.execute_script('return window._bokeh_render_complete;'))
try:
WebDriverWait(driver, timeout, poll_frequency=0.1).until(is_bokeh_render_complete)
except TimeoutException:
log.warning("The webdriver raised a TimeoutException while waiting for "
"a 'bokeh:idle' event to signify that the layout has rendered. "
"Something may have gone wrong.")
finally:
_log_console(driver) |
|
Install a new notebook display hook.
Bokeh comes with support for Jupyter notebooks built-in. However, there are
other kinds of notebooks in use by different communities. This function
provides a mechanism for other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A function for loading BokehJS in a notebook type. The function
will be called with the following arguments:
.. code-block:: python
load(
resources, # A Resources object for how to load BokehJS
verbose, # Whether to display verbose loading banner
hide_banner, # Whether to hide the output banner entirely
load_timeout # Time after which to report a load fail error
)
show_doc (callable) :
A function for displaying Bokeh standalone documents in the
notebook type. This function will be called with the following
arguments:
.. code-block:: python
show_doc(
obj, # the Bokeh object to display
state, # current bokeh.io "state"
notebook_handle # whether a notebook handle was requested
)
If the notebook platform is capable of supporting in-place updates
to plots then this function may return an opaque notebook handle
that can be used for that purpose. The handle will be returned by
``show()``, and can be used by as appropriate to update plots, etc.
by additional functions in the library that installed the hooks.
show_app (callable) :
A function for displaying Bokeh applications in the notebook
type. This function will be called with the following arguments:
.. code-block:: python
show_app(
app, # the Bokeh Application to display
state, # current bokeh.io "state"
notebook_url, # URL to the current active notebook page
**kw # any backend-specific keywords passed as-is
)
overwrite (bool, optional) :
Whether to allow an existing hook to be overwritten by a new
definition (default: False)
Returns:
None
Raises:
RuntimeError
If ``notebook_type`` is already installed and ``overwrite=False`` | def install_notebook_hook(notebook_type: NotebookType, load: Load, show_doc: ShowDoc,
show_app: ShowApp, overwrite: bool = False) -> None:
''' Install a new notebook display hook.
Bokeh comes with support for Jupyter notebooks built-in. However, there are
other kinds of notebooks in use by different communities. This function
provides a mechanism for other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A function for loading BokehJS in a notebook type. The function
will be called with the following arguments:
.. code-block:: python
load(
resources, # A Resources object for how to load BokehJS
verbose, # Whether to display verbose loading banner
hide_banner, # Whether to hide the output banner entirely
load_timeout # Time after which to report a load fail error
)
show_doc (callable) :
A function for displaying Bokeh standalone documents in the
notebook type. This function will be called with the following
arguments:
.. code-block:: python
show_doc(
obj, # the Bokeh object to display
state, # current bokeh.io "state"
notebook_handle # whether a notebook handle was requested
)
If the notebook platform is capable of supporting in-place updates
to plots then this function may return an opaque notebook handle
that can be used for that purpose. The handle will be returned by
``show()``, and can be used by as appropriate to update plots, etc.
by additional functions in the library that installed the hooks.
show_app (callable) :
A function for displaying Bokeh applications in the notebook
type. This function will be called with the following arguments:
.. code-block:: python
show_app(
app, # the Bokeh Application to display
state, # current bokeh.io "state"
notebook_url, # URL to the current active notebook page
**kw # any backend-specific keywords passed as-is
)
overwrite (bool, optional) :
Whether to allow an existing hook to be overwritten by a new
definition (default: False)
Returns:
None
Raises:
RuntimeError
If ``notebook_type`` is already installed and ``overwrite=False``
'''
if notebook_type in _HOOKS and not overwrite:
raise RuntimeError(f"hook for notebook type {notebook_type!r} already exists")
_HOOKS[notebook_type] = Hooks(load=load, doc=show_doc, app=show_app) |
Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working inside the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle object that can be used to update the Bokeh output later. When
``push_notebook`` is called, any property updates (e.g. plot titles or
data source values, etc.) since the last call to ``push_notebook`` or
the original ``show`` call are applied to the Bokeh output in the
previously rendered Jupyter output cell.
Several example notebooks can be found in the GitHub repository in
the :bokeh-tree:`examples/output/jupyter/push_notebook` directory.
Args:
document (Document, optional):
A |Document| to push from. If None uses ``curdoc()``. (default:
None)
state (State, optional) :
A :class:`State` object. If None, then the current default
state (set by |output_file|, etc.) is used. (default: None)
Returns:
None
Examples:
Typical usage is typically similar to this:
.. code-block:: python
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
output_notebook()
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# Update the plot title in the earlier cell
plot.title.text = "New Title"
push_notebook(handle=handle) | def push_notebook(*, document: Document | None = None, state: State | None = None,
handle: CommsHandle | None = None) -> None:
''' Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working inside the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle object that can be used to update the Bokeh output later. When
``push_notebook`` is called, any property updates (e.g. plot titles or
data source values, etc.) since the last call to ``push_notebook`` or
the original ``show`` call are applied to the Bokeh output in the
previously rendered Jupyter output cell.
Several example notebooks can be found in the GitHub repository in
the :bokeh-tree:`examples/output/jupyter/push_notebook` directory.
Args:
document (Document, optional):
A |Document| to push from. If None uses ``curdoc()``. (default:
None)
state (State, optional) :
A :class:`State` object. If None, then the current default
state (set by |output_file|, etc.) is used. (default: None)
Returns:
None
Examples:
Typical usage is typically similar to this:
.. code-block:: python
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
output_notebook()
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# Update the plot title in the earlier cell
plot.title.text = "New Title"
push_notebook(handle=handle)
'''
from ..protocol import Protocol as BokehProtocol
if state is None:
state = curstate()
if not document:
document = state.document
if not document:
warn("No document to push")
return
if handle is None:
handle = state.last_comms_handle
if not handle:
warn("Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()")
return
events = list(handle.doc.callbacks._held_events)
# This is to avoid having an exception raised for attempting to create a
# PATCH-DOC with no events. In the notebook, we just want to silently
# ignore calls to push_notebook when there are no new events
if len(events) == 0:
return
handle.doc.callbacks._held_events = []
msg = BokehProtocol().create("PATCH-DOC", cast(list["DocumentPatchedEvent"], events)) # XXX: either fix types or filter events
handle.comms.send(msg.header_json)
handle.comms.send(msg.metadata_json)
handle.comms.send(msg.content_json)
for buffer in msg.buffers:
header = json.dumps(buffer.ref)
payload = buffer.to_bytes()
handle.comms.send(header)
handle.comms.send(buffers=[payload]) |
Run an installed notebook hook with supplied arguments.
Args:
notebook_type (str) :
Name of an existing installed notebook hook
action (str) :
Name of the hook action to execute, ``'doc'`` or ``'app'``
All other arguments and keyword arguments are passed to the hook action
exactly as supplied.
Returns:
Result of the hook action, as-is
Raises:
RuntimeError
If the hook or specific action is not installed | def run_notebook_hook(notebook_type: NotebookType, action: Literal["load", "doc", "app"], *args: Any, **kwargs: Any) -> Any:
''' Run an installed notebook hook with supplied arguments.
Args:
notebook_type (str) :
Name of an existing installed notebook hook
action (str) :
Name of the hook action to execute, ``'doc'`` or ``'app'``
All other arguments and keyword arguments are passed to the hook action
exactly as supplied.
Returns:
Result of the hook action, as-is
Raises:
RuntimeError
If the hook or specific action is not installed
'''
if notebook_type not in _HOOKS:
raise RuntimeError(f"no display hook installed for notebook type {notebook_type!r}")
if _HOOKS[notebook_type][action] is None:
raise RuntimeError(f"notebook hook for {notebook_type!r} did not install {action!r} action")
return _HOOKS[notebook_type][action](*args, **kwargs) |
Given a UUID id of a div removed or replaced in the Jupyter
notebook, destroy the corresponding server sessions and stop it. | def destroy_server(server_id: ID) -> None:
''' Given a UUID id of a div removed or replaced in the Jupyter
notebook, destroy the corresponding server sessions and stop it.
'''
server = curstate().uuid_to_server.get(server_id, None)
if server is None:
log.debug(f"No server instance found for uuid: {server_id!r}")
return
try:
for session in server.get_sessions():
session.destroy()
server.stop()
del curstate().uuid_to_server[server_id]
except Exception as e:
log.debug(f"Could not destroy server for id {server_id!r}: {e}") |
Create a Jupyter comms object for a specific target, that can
be used to update Bokeh documents in the Jupyter notebook.
Args:
target_name (str) : the target name the Comms object should connect to
Returns
Jupyter Comms | def get_comms(target_name: str) -> Comm:
''' Create a Jupyter comms object for a specific target, that can
be used to update Bokeh documents in the Jupyter notebook.
Args:
target_name (str) : the target name the Comms object should connect to
Returns
Jupyter Comms
'''
# NOTE: must defer all IPython imports inside functions
from ipykernel.comm import Comm
return Comm(target_name=target_name, data={}) |
def install_jupyter_hooks() -> None:
'''
'''
install_notebook_hook('jupyter', load_notebook, show_doc, show_app) |
|
Prepare the IPython notebook for displaying Bokeh plots.
Args:
resources (Resource, optional) :
how and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to report detailed settings (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
.. warning::
Clearing the output cell containing the published BokehJS
resources HTML code may cause Bokeh CSS styling to be removed.
Returns:
None | def load_notebook(resources: Resources | None = None, verbose: bool = False,
hide_banner: bool = False, load_timeout: int = 5000) -> None:
''' Prepare the IPython notebook for displaying Bokeh plots.
Args:
resources (Resource, optional) :
how and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to report detailed settings (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
.. warning::
Clearing the output cell containing the published BokehJS
resources HTML code may cause Bokeh CSS styling to be removed.
Returns:
None
'''
global _NOTEBOOK_LOADED
from .. import __version__
from ..core.templates import NOTEBOOK_LOAD
from ..embed.bundle import bundle_for_objs_and_resources
from ..resources import Resources
from ..settings import settings
from ..util.serialization import make_globally_unique_css_safe_id
if resources is None:
resources = Resources(mode=settings.resources())
element_id: ID | None
html: str | None
if not hide_banner:
if resources.mode == 'inline':
js_info: str | list[str] = 'inline'
css_info: str | list[str] = 'inline'
else:
js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files
css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files
warnings = ["Warning: " + msg.text for msg in resources.messages if msg.type == 'warn']
if _NOTEBOOK_LOADED and verbose:
warnings.append('Warning: BokehJS previously loaded')
element_id = make_globally_unique_css_safe_id()
html = NOTEBOOK_LOAD.render(
element_id = element_id,
verbose = verbose,
js_info = js_info,
css_info = css_info,
bokeh_version = __version__,
warnings = warnings,
)
else:
element_id = None
html = None
_NOTEBOOK_LOADED = resources
bundle = bundle_for_objs_and_resources(None, resources)
nb_js = _loading_js(bundle, element_id, load_timeout, register_mime=True)
jl_js = _loading_js(bundle, element_id, load_timeout, register_mime=False)
if html is not None:
publish_display_data({'text/html': html})
publish_display_data({
JS_MIME_TYPE: nb_js,
LOAD_MIME_TYPE: jl_js,
}) |
def publish_display_data(data: dict[str, Any], metadata: dict[Any, Any] | None = None, *, transient: dict[str, Any] | None = None, **kwargs: Any) -> None:
'''
'''
# This import MUST be deferred or it will introduce a hard dependency on IPython
from IPython.display import publish_display_data
publish_display_data(data, metadata, transient=transient, **kwargs) |
|
Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a string, the value string is parsed to
construct the origin and full server URLs.
If notebook_url is a callable, it must accept one parameter,
which will be the server port, or None. If passed a port,
the callable must generate the server URL, otherwise if passed
None, it must generate the origin URL for the server.
If the environment variable JUPYTER_BOKEH_EXTERNAL_URL is set
to the external URL of a JupyterHub, notebook_url is overridden
with a callable which enables Bokeh to traverse the JupyterHub
proxy without specifying this parameter.
port (int) :
A port for the embedded server will listen on.
By default the port is 0, which results in the server listening
on a random dynamic port.
Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)
Returns:
None | def show_app(
app: Application,
state: State,
notebook_url: str | ProxyUrlFunc = DEFAULT_JUPYTER_URL,
port: int = 0,
**kw: Any,
) -> None:
''' Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a string, the value string is parsed to
construct the origin and full server URLs.
If notebook_url is a callable, it must accept one parameter,
which will be the server port, or None. If passed a port,
the callable must generate the server URL, otherwise if passed
None, it must generate the origin URL for the server.
If the environment variable JUPYTER_BOKEH_EXTERNAL_URL is set
to the external URL of a JupyterHub, notebook_url is overridden
with a callable which enables Bokeh to traverse the JupyterHub
proxy without specifying this parameter.
port (int) :
A port for the embedded server will listen on.
By default the port is 0, which results in the server listening
on a random dynamic port.
Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)
Returns:
None
'''
logging.basicConfig()
from tornado.ioloop import IOLoop
from ..server.server import Server
loop = IOLoop.current()
notebook_url = _update_notebook_url_from_env(notebook_url)
if callable(notebook_url):
origin = notebook_url(None)
else:
origin = _origin_url(notebook_url)
server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw)
server_id = ID(uuid4().hex)
curstate().uuid_to_server[server_id] = server
server.start()
if callable(notebook_url):
url = notebook_url(server.port)
else:
url = _server_url(notebook_url, server.port)
logging.debug(f"Server URL is {url}")
logging.debug(f"Origin URL is {origin}")
from ..embed import server_document
script = server_document(url, resources=None)
publish_display_data({
HTML_MIME_TYPE: script,
EXEC_MIME_TYPE: "",
}, metadata={
EXEC_MIME_TYPE: {"server_id": server_id},
}) |
def show_doc(obj: Model, state: State, notebook_handle: CommsHandle | None = None) -> CommsHandle | None:
'''
'''
if obj not in state.document.roots:
state.document.add_root(obj)
from ..embed.notebook import notebook_content
comms_target = make_id() if notebook_handle else None
(script, div, cell_doc) = notebook_content(obj, comms_target)
publish_display_data({HTML_MIME_TYPE: div})
publish_display_data({JS_MIME_TYPE: script, EXEC_MIME_TYPE: ""}, metadata={EXEC_MIME_TYPE: {"id": obj.id}})
# Comms handling relies on the fact that the cell_doc returned by
# notebook copy has models with the same IDs as the original curdoc
# they were copied from
if comms_target:
handle = CommsHandle(get_comms(comms_target), cell_doc)
state.document.callbacks.on_change_dispatch_to(handle)
state.last_comms_handle = handle
return handle
return None |
|
def _loading_js(bundle: Bundle, element_id: ID | None, load_timeout: int = 5000, register_mime: bool = True) -> str:
'''
'''
from ..core.templates import AUTOLOAD_NB_JS
return AUTOLOAD_NB_JS.render(
bundle = bundle,
elementid = element_id,
force = True,
timeout = load_timeout,
register_mime = register_mime,
) |
|
def _origin_url(url: str) -> str:
'''
'''
if url.startswith("http"):
url = url.split("//")[1]
return url |
|
def _server_url(url: str, port: int | None) -> str:
'''
'''
port_ = f":{port}" if port is not None else ""
if url.startswith("http"):
return f"{url.rsplit(':', 1)[0]}{port_}{'/'}"
else:
return f"http://{url.split(':')[0]}{port_}{'/'}" |
|
Callable to configure Bokeh's show method when a proxy must be
configured. If port is None we're asking about the URL
for the origin header.
Taken from documentation here:
https://docs.bokeh.org/en/latest/docs/user_guide/output/jupyter.html#jupyterhub
and made an implicit override when JUPYTER_BOKEH_EXTERNAL_URL is defined in
a user's environment to the external hostname of the hub, e.g. https://our-hub.edu
Args:
port (int):
random port generated by bokeh to avoid re-using recently closed ports
Returns:
str:
URL capable of traversing the JupyterHub proxy to return to this notebook session. | def _remote_jupyter_proxy_url(port: int | None) -> str:
""" Callable to configure Bokeh's show method when a proxy must be
configured. If port is None we're asking about the URL
for the origin header.
Taken from documentation here:
https://docs.bokeh.org/en/latest/docs/user_guide/output/jupyter.html#jupyterhub
and made an implicit override when JUPYTER_BOKEH_EXTERNAL_URL is defined in
a user's environment to the external hostname of the hub, e.g. https://our-hub.edu
Args:
port (int):
random port generated by bokeh to avoid re-using recently closed ports
Returns:
str:
URL capable of traversing the JupyterHub proxy to return to this notebook session.
"""
base_url = os.environ['JUPYTER_BOKEH_EXTERNAL_URL']
host = urllib.parse.urlparse(base_url).netloc
# If port is None we're asking for the URL origin
# so return the public hostname.
if port is None:
return host
service_url_path = os.environ['JUPYTERHUB_SERVICE_PREFIX']
proxy_url_path = f'proxy/{port}'
user_url = urllib.parse.urljoin(base_url, service_url_path)
full_url = urllib.parse.urljoin(user_url, proxy_url_path)
return full_url |
If the environment variable ``JUPYTER_BOKEH_EXTERNAL_URL`` is defined, returns a function which
generates URLs which can traverse the JupyterHub proxy. Otherwise returns ``notebook_url`` unmodified.
A warning is issued if ``notebook_url`` is not the default and
``JUPYTER_BOKEH_EXTERNAL_URL`` is also defined since setting the
environment variable makes specifying ``notebook_url`` irrelevant.
Args:
notebook_url (str | ProxyUrlFunc):
Either a URL string which defaults or a function that given a port
number will generate a URL suitable for traversing the JupyterHub proxy.
Returns:
str | ProxyUrlFunc
Either a URL string or a function that generates a URL string given a port number. The
latter function may be user supplied as the input parameter or defined internally by Bokeh
when ``JUPYTER_BOKEH_EXTERNAL_URL`` is set. | def _update_notebook_url_from_env(notebook_url: str | ProxyUrlFunc) -> str | ProxyUrlFunc:
"""If the environment variable ``JUPYTER_BOKEH_EXTERNAL_URL`` is defined, returns a function which
generates URLs which can traverse the JupyterHub proxy. Otherwise returns ``notebook_url`` unmodified.
A warning is issued if ``notebook_url`` is not the default and
``JUPYTER_BOKEH_EXTERNAL_URL`` is also defined since setting the
environment variable makes specifying ``notebook_url`` irrelevant.
Args:
notebook_url (str | ProxyUrlFunc):
Either a URL string which defaults or a function that given a port
number will generate a URL suitable for traversing the JupyterHub proxy.
Returns:
str | ProxyUrlFunc
Either a URL string or a function that generates a URL string given a port number. The
latter function may be user supplied as the input parameter or defined internally by Bokeh
when ``JUPYTER_BOKEH_EXTERNAL_URL`` is set.
"""
if os.environ.get("JUPYTER_BOKEH_EXTERNAL_URL"):
if notebook_url != DEFAULT_JUPYTER_URL:
log.warning("Environment var 'JUPYTER_BOKEH_EXTERNAL_URL' is defined. Ignoring 'notebook_url' parameter.")
return _remote_jupyter_proxy_url
else:
return notebook_url |
Configure the default output state to generate output saved
to a file when :func:`show` is called.
Does not change the current ``Document`` from ``curdoc()``. File and notebook
output may be active at the same time, so e.g., this does not clear the
effects of ``output_notebook()``.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document (default: "Bokeh Plot")
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details.
root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or
``CDN``.
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
.. warning::
This output file will be overwritten on every save, e.g., each time
|show| or |save| is invoked. | def output_file(filename: PathLike, title: str = "Bokeh Plot",
mode: ResourcesMode | None = None, root_dir: PathLike | None = None) -> None:
''' Configure the default output state to generate output saved
to a file when :func:`show` is called.
Does not change the current ``Document`` from ``curdoc()``. File and notebook
output may be active at the same time, so e.g., this does not clear the
effects of ``output_notebook()``.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document (default: "Bokeh Plot")
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details.
root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or
``CDN``.
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
.. warning::
This output file will be overwritten on every save, e.g., each time
|show| or |save| is invoked.
'''
curstate().output_file(
filename,
title=title,
mode=mode,
root_dir=root_dir,
) |
Configure the default output state to generate output in notebook cells
when |show| is called. Note that |show| may be called multiple
times in a single cell to display multiple objects in the output cell. The
objects will be displayed in order.
Args:
resources (Resource, optional) :
How and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to display detailed BokehJS banner (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
notebook_type (string, optional):
Notebook type (default: jupyter)
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script. | def output_notebook(resources: Resources | None = None, verbose: bool = False,
hide_banner: bool = False, load_timeout: int = 5000, notebook_type: NotebookType = "jupyter") -> None:
''' Configure the default output state to generate output in notebook cells
when |show| is called. Note that |show| may be called multiple
times in a single cell to display multiple objects in the output cell. The
objects will be displayed in order.
Args:
resources (Resource, optional) :
How and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to display detailed BokehJS banner (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
notebook_type (string, optional):
Notebook type (default: jupyter)
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
'''
# verify notebook_type first in curstate().output_notebook
curstate().output_notebook(notebook_type)
run_notebook_hook(notebook_type, "load", resources, verbose, hide_banner, load_timeout) |
Clear the default state of all output modes.
Returns:
None | def reset_output(state: State | None = None) -> None:
''' Clear the default state of all output modes.
Returns:
None
'''
curstate().reset() |
Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived from the script name (e.g. ``/foo/myplot.py`` will create
``/foo/myplot.html``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, use the default state configuration.
resources (Resources or ResourcesMode, optional) : A Resources config to use (default: None)
If None, use the default state configuration, if there is one.
otherwise use ``resources.INLINE``.
title (str, optional) : a title for the HTML document (default: None)
If None, use the default state title value, if there is one.
Otherwise, use "Bokeh Plot"
template (Template, str, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required template
parameters
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
str: the filename where the HTML file is saved. | def save(obj: UIElement | Sequence[UIElement], filename: PathLike | None = None, resources: ResourcesLike | None = None,
title: str | None = None, template: Template | str | None = None, state: State | None = None) -> str:
''' Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived from the script name (e.g. ``/foo/myplot.py`` will create
``/foo/myplot.html``)
Args:
obj (UIElement object) : a Layout (Row/Column), Plot or Widget object to display
filename (PathLike, e.g. str, Path, optional) : filename to save document under (default: None)
If None, use the default state configuration.
resources (Resources or ResourcesMode, optional) : A Resources config to use (default: None)
If None, use the default state configuration, if there is one.
otherwise use ``resources.INLINE``.
title (str, optional) : a title for the HTML document (default: None)
If None, use the default state title value, if there is one.
Otherwise, use "Bokeh Plot"
template (Template, str, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required template
parameters
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
str: the filename where the HTML file is saved.
'''
if state is None:
state = curstate()
theme = state.document.theme
filename, resources, title = _get_save_args(state, filename, resources, title)
_save_helper(obj, filename, resources, title, template, theme)
return abspath(expanduser(filename)) |
def _get_save_args(state: State, filename: PathLike | None, resources: ResourcesLike | None,
title: str | None) -> tuple[PathLike, Resources, str]:
'''
'''
filename, is_default_filename = _get_save_filename(state, filename)
resources = _get_save_resources(state, resources, is_default_filename)
title = _get_save_title(state, title, is_default_filename)
return filename, resources, title |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.