panel.io.server module#

Utilities for creating bokeh Server instances.

class panel.io.server.AdminLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

Serves the password login page of the admin panel.

Methods

get

post

class panel.io.server.AdminLogoutHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

Clears the admin cookie and returns to the admin login page.

Methods

get

class panel.io.server.AuthenticatedStaticFileHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: LoginUrlMixin, StaticFileHandler

Methods

compute_etag()

Sets the Etag header based on static url version.

get_current_user()

Delegate to the synchronous get_user method of the auth provider

prepare()

Async counterpart to get_current_user

get

compute_etag()[source]#

Sets the Etag header based on static url version.

This allows efficient If-None-Match checks against cached versions, and sends the correct Etag for a partial response (i.e. the same Etag as the full file).

Added in version 3.1.

get_current_user()[source]#

Delegate to the synchronous get_user method of the auth provider

async prepare()[source]#

Async counterpart to get_current_user

class panel.io.server.AuthorizationResult(authorized: bool | None, error: str | None, redirect: str | None = None)[source]#

Bases: NamedTuple

Outcome of evaluating config.authorize_callback for a request.

authorized is None when the callback asked for a redirect, in which case redirect holds the target URL.

authorized: bool | None#

Alias for field number 0

error: str | None#

Alias for field number 1

redirect: str | None#

Alias for field number 2

class panel.io.server.AutoloadJsHandler(tornado_app: BokehTornado, *args: Any, **kw: Any)[source]#

Bases: AutoloadJsHandler

Implements a custom Tornado handler for the autoload JS chunk

Methods

options(*args, **kwargs)

Browsers make OPTIONS requests under the hood before a GET request

set_default_headers()

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

get

get_session

async options(*args, **kwargs) → None[source]#

Browsers make OPTIONS requests under the hood before a GET request

set_default_headers() → None[source]#

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

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

class panel.io.server.ComponentResourceHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: PrecompressedStaticMixin, StaticFileHandler

A handler that serves local resources relative to a Python module. The handler resolves a specific Panel component by module reference and name, then resolves an attribute on that component to check if it contains the requested resource path.

/<endpoint>/<module>/<class>/<attribute>/<path>

Methods

get_absolute_path(root, path)

Returns the absolute location of path relative to root.

parse_url_path(path)

Resolves the resource the URL pattern refers to.

validate_absolute_path(root, absolute_path)

Validate and return the absolute path.

initialize

classmethod get_absolute_path(root: str, path: str) → str[source]#

Returns the absolute location of path relative to root.

root is the path configured for this StaticFileHandler (in most cases the static_path Application setting).

This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass’s overridden get_content.

Raises HTTPError (403) if path leads outside of root (as written, e.g. with ../; symlinks are checked later by validate_absolute_path). This check is also what keeps get_version (and therefore ~RequestHandler.static_url) from reading files outside of the static directory.

Added in version 3.1.

Changed in version 6.6: Paths outside of root now raise HTTPError.

initialize(path: str | Literal['root'] = 'root', default_filename: str | None = None, *args: Any, **kwargs: Any)[source]#
parse_url_path(path: str) → str[source]#

Resolves the resource the URL pattern refers to.

validate_absolute_path(root: str, absolute_path: str) → str[source]#

Validate and return the absolute path.

root is the configured path for the StaticFileHandler, and path is the result of get_absolute_path

This is an instance method called during request processing, so it may raise HTTPError or use methods like RequestHandler.redirect (return None after redirecting to halt further processing). This is where 404 errors for missing files are generated.

This method may modify the path before returning it, but note that any such modifications will not be understood by make_static_url.

In instance methods, this method’s result is available as self.absolute_path.

Added in version 3.1.

class panel.io.server.DocHandler(tornado_app: BokehTornado, *args: Any, **kw: Any)[source]#

Bases: LoginUrlMixin, DocHandler

Methods

get

get_session

class panel.io.server.ExtensionStaticHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: PrecompressedStaticMixin, MultiRootStaticHandler

Serves the static/extensions/ resources of Panel and other extensions, caching versioned urls as long as Bokeh caches its own ?v= urls.

Methods

get_cache_time(path, modified, mime_type)

Override to customize cache control behavior.

get_cache_time(path: str, modified, mime_type: str) → int[source]#

Override to customize cache control behavior.

Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics).

By default returns cache expiry of 10 years for resources requested with v argument.

class panel.io.server.LoginUrlMixin[source]#

Bases: object

Overrides the AuthRequestHandler.get_login_url implementation to correctly handle prefixes.

Methods

get_login_url()

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

get_login_url()[source]#

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

class panel.io.server.PanelStaticHandler(tornado_app: Any, *args: Any, **kw: Any)[source]#

Bases: PrecompressedStaticMixin, StaticHandler

Serves Bokeh’s static resources, compressing each file once.

class panel.io.server.PrecompressedStaticMixin[source]#

Bases: object

Serves compressible static files gzipped from an in-memory cache.

Tornado’s compress_response gzips every response again on the event loop, which for the megabytes of JavaScript a page loads costs more time than the smaller transfer saves, so each file is compressed once instead. Responses that already carry a Content-Encoding are left alone by Tornado’s transform.

Methods

get

class panel.io.server.ProxyFallbackHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

A RequestHandler that wraps another HTTP server callback and proxies the subpath.

Methods

prepare()

Called at the beginning of a request before get/post/etc.

initialize

initialize(fallback, proxy=None)[source]#
prepare()[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method. There is no guarantee that prepare will be called if an error occurs that is handled by the framework.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

class panel.io.server.RootHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: LoginUrlMixin, RootHandler

Custom RootHandler that provides the CDN_DIST directory as a template variable.

Methods

render(*args, **kwargs)

Renders the template with the given arguments as the response.

get

render(*args, **kwargs)[source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

class panel.io.server.Server(*args, **kwargs)[source]#

Bases: Server

Methods

start()

Install the Bokeh Server and its background tasks on a Tornado IOLoop.

stop([wait])

Stop the Bokeh Server.

stop_async()

Stop the Bokeh Server and await orderly application cleanup.

start() → None[source]#

Install the Bokeh Server and its background tasks on a Tornado IOLoop.

This method does not block and does not affect the state of the Tornado IOLoop You must start and stop the loop yourself, i.e. this method is typically useful when you are already explicitly managing an IOLoop yourself.

To start a Bokeh server and immediately “run forever” in a blocking manner, see run_until_shutdown().

stop(wait: bool = True) → None[source]#

Stop the Bokeh Server.

This stops and removes all Bokeh Server IOLoop callbacks, as well as stops the HTTPServer that this instance was configured with.

Args:
wait (bool):

Whether to wait for orderly cleanup (default: True)

A synchronous call made from the server’s own running event loop cannot block that loop. In that case cleanup is scheduled and this method returns; await wait_until_stopped() for the completion barrier. Async callers may instead use stop_async() directly.

Returns:

None

async stop_async() → None[source]#

Stop the Bokeh Server and await orderly application cleanup.

Use this instead of stop() from async code when subsequent work depends on all sessions and lifecycle hooks having finished. Like stop(), this method may only be called once.

class panel.io.server.SessionInfoHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: LoginUrlMixin, AuthRequestHandler

Serves state.session_info as JSON, matching PanelASGI’s /session_info endpoint.

Methods

get

head

initialize

initialize(legacy: bool = False)[source]#
class panel.io.server.WSHandler(tornado_app: Application, *args: Any, **kw: Any)[source]#

Bases: WSHandler

Methods

open(*args, **kwargs)

Initialize a connection to a client.

prepare()

Async counterpart to get_current_user

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

Initialize a connection to a client.

Returns:

None

async prepare()[source]#

Async counterpart to get_current_user

panel.io.server.admin_auth_patterns(admin_path: str) → list[tuple[str, type[RequestHandler]]][source]#

The routes of the admin login and logout pages, if the admin panel is password protected.

panel.io.server.async_execute(func: Callable[..., None]) → None[source]#

Wrap async event loop scheduling to ensure that with_lock flag is propagated from function to partial wrapping it.

panel.io.server.authorize_app_request(application: t.Any, request: t.Any, payload: TokenPayload | dict[str, t.Any], suffix: str = '') → AuthorizationResult[source]#

Run the global authorization callback for a request to an application route, e.g. its document, autoload.js or websocket.

The callback receives the path of the application itself, i.e. the request path without the route suffix, and reads the user from a temporary session built from the request payload.

panel.io.server.authorize_request(path: str, session: bool = False) → AuthorizationResult[source]#

Determine whether the current user is authorized to access an app.

Parameters:
path: str

The URL path the user is trying to access.

session: bool

Whether the check is being performed inside a session, in which case a globally configured callback is skipped since it already ran for the HTTP request.

panel.io.server.autoload_cors_headers(request: Any, allowlist: Sequence[str], preflight: bool = False) → dict[str, str][source]#

The CORS headers of an autoload.js response. Credentialed requests, e.g. the XHR server_document issues when given headers, are only allowed from the origin of the request itself and the credential allowlist.

panel.io.server.bind_request_user(request: Any, user: Any) → None[source]#

Records the user a request was authenticated as on the request, so that a session it creates is bound to that user.

panel.io.server.client_token(app: Any, context: Any, request: Any, token: str) → str[source]#

Returns the token a request presenting token creates or opens its session with, see client_token_payload.

panel.io.server.client_token_payload(app: Any, context: Any, session_id: str, request: Any, token: str, payload: dict[str, Any]) → dict[str, Any][source]#

Returns the payload a request presenting a session token creates or opens the session with.

An unsigned token can be built by the client, so when it creates the session the headers and cookies are taken from the request itself rather than from the token, unless the server issued the token.

Parameters:
app:

The BokehTornado application or BokehServerCore.

context:

The ApplicationContext the session belongs to.

session_id:

The id of the session the token refers to.

request:

The request presenting the token.

token:

The token the request presented.

payload:

The payload of the token.

panel.io.server.compile_route_template(route: str) → tuple[str, tuple[str, ...]][source]#

Translate a FastAPI-style route template into a regex source string and the tuple of parameter names it captures.

Literal segments are escaped so that a mixed route such as /user/{name}/detail matches only the literal parts it declares.

panel.io.server.credential_allowlist(websocket_origins: Iterable[str]) → list[str][source]#

The hosts whose pages may receive credentials from autoload.js, i.e. the hosts allowed to open a websocket (--allow-websocket-origin or BOKEH_ALLOW_WS_ORIGIN) except catch-all * entries, which allow connections from anywhere but do not vouch for any particular page.

panel.io.server.credentials_allowed(request: Any, allowlist: Sequence[str]) → bool[source]#

Whether the session token generated for request may carry the credentials it was sent with, i.e. its cookies and authorization headers.

A browser attaches cookies to requests for scripts included by any page, so a script embedding a session token must only carry them when the page including it is allowed to connect to the websocket anyway. The page is identified by the Sec-Fetch-Site header when it reports a same-origin request, and otherwise by the Origin header or, for a plain <script> include which does not send one, the Referer header. Browsers omit Sec-Fetch-Site for plain http servers, so its absence does not prove anything. Requests without any of these headers do not identify a page, e.g. those of non-browser clients, and are allowed.

panel.io.server.get_server(panel: TViewableFuncOrPath | dict[str, TViewableFuncOrPath], port: int = 0, address: str | None = None, websocket_origin: str | list[str] | None = None, loop: IOLoop | None = None, show: bool = False, start: bool = False, title: str | dict[str, str] | None = None, verbose: bool = False, location: bool | Location = True, admin: bool = False, static_dirs: Mapping[str, str] = {}, basic_auth: str | None = None, oauth_provider: str | None = None, oauth_key: str | None = None, oauth_secret: str | None = None, oauth_redirect_uri: str | None = None, oauth_extra_params: Mapping[str, str] = {}, oauth_error_template: str | None = None, cookie_path: str = '/', cookie_secret: str | None = None, oauth_encryption_key: str | None = None, oauth_jwt_user: str | None = None, oauth_refresh_tokens: bool | None = None, oauth_guest_endpoints: list[str] | None = None, oauth_optional: bool | None = None, root_path: str | None = None, login_endpoint: str | None = None, logout_endpoint: str | None = None, login_template: str | None = None, logout_template: str | None = None, session_history: str | None = None, liveness: bool | str = False, warm: bool = False, compress: bool = True, **kwargs) → Server[source]#

Returns a Server instance with this panel attached as the root app.

Parameters:
panel: Viewable, function or {str: Viewable}

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

port: int (optional, default=0)

Allows specifying a specific port

addressstr

The address the server should listen on for HTTP requests.

websocket_origin: str or list(str) (optional)

A list of hosts that can connect to the websocket.

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

If None, “localhost” is used.

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

The tornado IOLoop to run the Server on.

showboolean (optional, default=False)

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

startboolean(optional, default=False)

Whether to start the Server.

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

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

verbose: boolean (optional, default=False)

Whether to report the address and port.

locationboolean or panel.io.location.Location

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

admin: boolean (default=False)

Whether to enable the admin panel

static_dirs: dict (optional, default={})

A dictionary of routes and local paths to serve as static file directories on those routes.

basic_auth: str (optional, default=None)

Password or filepath to use with basic auth provider.

oauth_provider: str

One of the available OAuth providers

oauth_key: str (optional, default=None)

The public OAuth identifier

oauth_secret: str (optional, default=None)

The client secret for the OAuth provider

oauth_redirect_uri: Optional[str] = None,

Overrides the default OAuth redirect URI, which is the public URL of the server including the root_path and prefix.

oauth_extra_params: dict (optional, default={})

Additional information for the OAuth provider

oauth_error_template: str (optional, default=None)

Jinja2 template used when displaying authentication errors.

cookie_path: str (optional, default=’/’)

The sub path of the domain the cookie is valid for.

cookie_secret: str (optional, default=None)

A random secret string to sign cookies (required for OAuth)

oauth_encryption_key: str (optional, default=None)

A random encryption key used for encrypting OAuth user information and access tokens.

oauth_jwt_user: Optional[str] = None,

Key that identifies the user in the JWT id_token.

oauth_refresh_tokens: bool (optional, default=None)

Whether to automatically refresh OAuth access tokens when they expire.

oauth_guest_endpoints: list (optional, default=None)

List of endpoints that can be accessed as a guest without authenticating. End an endpoint with /* to also cover the paths below it.

oauth_optional: bool (optional, default=None)

Whether the user will be forced to go through login flow or if they can access all applications as a guest.

root_path: str (optional, default=None)

The path a reverse proxy serves the application on if it strips that path from the requests it forwards. Used to build the login redirects and the default OAuth redirect URI and takes precedence over the X-Forwarded-Prefix header read with use_xheaders=True.

login_endpoint: str (optional, default=None)

Overrides the default login endpoint /login

logout_endpoint: str (optional, default=None)

Overrides the default logout endpoint /logout

logout_template: str (optional, default=None)

Jinja2 template served when viewing the login endpoint when authentication is enabled.

logout_template: str (optional, default=None)

Jinja2 template served when viewing the logout endpoint when authentication is enabled.

session_history: int (optional, default=None)

The amount of session history to accumulate. If set to non-zero and non-None value will launch an endpoint at /session_info, which returns information about the session history.

liveness: bool | str (optional, default=False)

Whether to add a liveness endpoint. If a string is provided then this will be used as the endpoint, otherwise the endpoint will be hosted at /liveness.

warm: bool (optional, default=False)

Whether to run the applications before serving them to ensure all imports and caches are fully warmed up before serving the app.

compress: bool (optional, default=True)

Whether to gzip HTTP responses (pages, scripts, stylesheets and JSON) for clients that accept it. Disable when a reverse proxy compresses responses already.

kwargs: dict

Additional keyword arguments to pass to Server instance.

Returns:
serverpanel.io.server.Server

Bokeh Server instance running this panel

panel.io.server.get_session_info_routes()[source]#

Returns the Tornado routes serving state.session_info.

panel.io.server.get_static_routes(static_dirs)[source]#

Returns a list of tornado routes of StaticFileHandlers given a dictionary of slugs and file paths to serve.

panel.io.server.html_page_for_render_items(bundle: Bundle | tuple[str, str], docs_json: dict[ID, DocJson], render_items: list[RenderItem], title: str, template: Template | str | None = None, template_variables: dict[str, t.Any] = {}) → str[source]#

Render an HTML page from a template and Bokeh render items.

Parameters:
bundle (tuple):

A tuple containing (bokehjs, bokehcss)

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
panel.io.server.index_page_items(app_paths: Iterable[str], prefix: str, index: str | None = None, uri: str = '/') → list[str] | list[tuple[str, str]][source]#

Compute the items rendered on the index page.

Without a custom index a sorted list of slugs is returned, matching Bokeh’s default template. With a custom index a sorted list of (slug, title) tuples is returned, applying config.index_titles.

panel.io.server.index_redirect(app_paths: Mapping[str, t.Any] | Iterable[str], use_redirect: bool) → str | None[source]#

Return the relative redirect target for the root URL, if the root should redirect to the single served application instead of rendering an index page.

panel.io.server.is_concrete_route(route: str) → bool[source]#

Whether a route is a literal path rather than a pattern or template.

panel.io.server.origin_allowed(origin: str, request: Any, allowlist: Sequence[str], same_host: bool = True) → bool[source]#

Whether origin, the value of an Origin or Referer header, is one of the allowlist hosts or, if same_host, the host of request itself.

panel.io.server.public_session_info() → dict[str, Any][source]#

Returns state.session_info with each session keyed by a digest of its id, since a session id is all a client needs to connect to it.

panel.io.server.register_issued_token(token: str, expiration: int) → None[source]#

Records an unsigned token the server issued for a session that the websocket will create, so that its payload is trusted when it does.

panel.io.server.render_auth_error(auth_error: str) → str[source]#

Render the authorization error page for the given message.

panel.io.server.render_index_page(app_paths: Iterable[str], prefix: str, index: str | None = None, uri: str = '/') → str[source]#

Render the index page listing the available applications.

Both the Bokeh default (app_index.html) and Panel’s own index are Tornado templates, so they are rendered with a tornado.template loader rooted at Bokeh’s views directory. Absolute index paths resolve correctly since os.path.join ignores the root for them, which is the same resolution Tornado’s RequestHandler.render performs.

panel.io.server.resolve_component_resource(path: str) → str[source]#

Resolve a component resource URL path to a file on disk.

ComponentResourceHandler.parse_url_path only ever accesses self._resource_attrs, which is a class attribute, so it can be called without instantiating the handler.

async panel.io.server.resolve_session(request: t.Any, create_session: Callable[[], Awaitable[ServerSession]], path: str | None = None) → ServerSession[source]#

Resolve the session for a request, reusing an existing session if config.reuse_sessions is enabled.

Parameters:
request:

The request the session is being created for.

create_session:

Zero-argument coroutine function creating a new session.

path: str

The application path, defaults to the request path.

panel.io.server.sanitize_token_argument(app: Any, context: Any, request: Any) → None[source]#

Applies client_token to the bokeh-token argument of an HTTP request, which creates the session when it does not exist yet.

panel.io.server.serve(panels: TViewableFuncOrPath | dict[str, TViewableFuncOrPath], port: int = 0, address: str | None = None, websocket_origin: str | list[str] | None = None, loop: IOLoop | None = None, show: bool = True, start: bool = True, title: str | None = None, verbose: bool = True, location: bool = True, threaded: bool = False, admin: bool = False, **kwargs) → StoppableThread | Server[source]#

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

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

Parameters:
panels: Viewable, function or {str: Viewable or function}

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

port: int (optional, default=0)

Allows specifying a specific port

addressstr

The address the server should listen on for HTTP requests.

websocket_origin: str or list(str) (optional)

A list of hosts that can connect to the websocket.

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

If None, “localhost” is used.

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

The tornado IOLoop to run the Server on

showboolean (optional, default=True)

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

startboolean(optional, default=True)

Whether to start the Server

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

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

verbose: boolean (optional, default=True)

Whether to print the address and port

locationboolean or panel.io.location.Location

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

threaded: boolean (default=False)

Whether to start the server on a new Thread

admin: boolean (default=False)

Whether to enable the admin panel

compress: boolean (default=True)

Whether to gzip HTTP responses for clients that accept it

kwargs: dict

Additional keyword arguments to pass to Server instance, e.g. prefix to serve everything under a URL prefix or use_xheaders=True to trust the X-Forwarded-* headers of a reverse proxy for the client IP and the public URL of the server.

panel.io.server.session_user_allowed(session: ServerSession, request: Any) → bool[source]#

Whether a request may connect to a session, i.e. it is authenticated as the user whose request created the session. Sessions created without an authenticated user, e.g. when authentication is not configured, are not bound to a user.

panel.io.server.strip_request_credentials(request: Any) → None[source]#

Removes the cookies, the authenticated user and all headers that may carry credentials from a Tornado HTTPServerRequest or a Bokeh ServerRequest so that a session created for it does not see them.

panel.io.server.token_payload_for_request(app: t.Any, request: t.Any) → TokenPayload[source]#

Build the session token payload for a request.

Parameters:
app:

An object declaring the include_headers, exclude_headers, include_cookies and exclude_cookies filters, i.e. either a BokehTornado application or a BokehServerCore.

request:

Any request exposing the bokeh.server.request.RequestLike interface, i.e. a Tornado HTTPServerRequest or a bokeh.server.request.ServerRequest.

panel.io.server.validate_static_dirs(static_dirs: Mapping[str, str]) → dict[str, str][source]#

Validate a mapping of URL slugs to static directories and return it with normalized slugs and absolute paths.