🔍 Code Extractor

class AutoloadJsHandler

Maturity: 49

A custom Tornado request handler that generates and serves the Bokeh autoload JavaScript chunk for embedding Bokeh applications in web pages.

File:
/tf/active/vicechatdev/patches/server.py
Lines:
231 - 263
Complexity:
complex

Purpose

This handler extends Bokeh's built-in AutoloadJsHandler to provide custom session management and resource handling for Panel/Bokeh applications. It generates JavaScript code that can be embedded in HTML pages to dynamically load and initialize Bokeh visualizations. The handler manages session state, resolves resource URLs, and produces the autoload script with proper configuration for the target element.

Source Code

class AutoloadJsHandler(BkAutoloadJsHandler, SessionPrefixHandler):
    ''' Implements a custom Tornado handler for the autoload JS chunk

    '''

    async def get(self, *args, **kwargs):
        element_id = self.get_argument("bokeh-autoload-element", default=None)
        if not element_id:
            self.send_error(status_code=400, reason='No bokeh-autoload-element query parameter')
            return

        app_path = self.get_argument("bokeh-app-path", default="/")
        absolute_url = self.get_argument("bokeh-absolute-url", default=None)

        if absolute_url:
            server_url = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(absolute_url))
        else:
            server_url = None

        with self._session_prefix():
            session = await self.get_session()
            state.curdoc = session.document
            try:
                resources = Resources.from_bokeh(self.application.resources(server_url))
                js = autoload_js_script(
                    session.document, resources, session.token, element_id,
                    app_path, absolute_url
                )
            finally:
                state.curdoc = None

        self.set_header("Content-Type", 'application/javascript')
        self.write(js)

Parameters

Name Type Default Kind
bases BkAutoloadJsHandler, SessionPrefixHandler -

Parameter Details

bases: Inherits from BkAutoloadJsHandler (Bokeh's base autoload handler) and SessionPrefixHandler (provides session prefix management). No explicit __init__ parameters are defined, so it uses the parent classes' constructors which expect Tornado application and request objects.

Return Value

The class itself returns an instance when instantiated. The get() method doesn't return a value but writes JavaScript content directly to the HTTP response via self.write(). On error, it sends a 400 status code with an error message.

Class Interface

Methods

async get(self, *args, **kwargs) -> None

Purpose: Handles HTTP GET requests to generate and serve the Bokeh autoload JavaScript chunk

Parameters:

  • *args: Variable positional arguments passed by Tornado routing (typically URL path components)
  • **kwargs: Variable keyword arguments passed by Tornado routing

Returns: None - writes JavaScript content directly to the HTTP response or sends error status

Attributes

Name Type Description Scope
application BkApplication Inherited from parent handler - the Bokeh application instance containing resources and configuration instance

Dependencies

  • tornado
  • bokeh
  • param
  • urllib

Required Imports

from bokeh.server.views.autoload_js_handler import AutoloadJsHandler as BkAutoloadJsHandler
from urllib.parse import urlparse
from resources import Resources
from state import state

Conditional/Optional Imports

These imports are only needed under specific conditions:

from bokeh.embed.bundle import Script

Condition: Required for generating autoload scripts

Required (conditional)
from bokeh.core.templates import AUTOLOAD_JS

Condition: Required for autoload JavaScript template

Required (conditional)

Usage Example

# This handler is typically registered with Tornado/Bokeh server, not instantiated directly
# Example of URL pattern registration:
from tornado.web import Application
from bokeh.server.urls import per_app_patterns

# Handler is registered in URL patterns
app_patterns = per_app_patterns(
    '/app',
    [(r'/autoload.js', AutoloadJsHandler)]
)

# Client-side usage - embed in HTML:
# <div id="myplot"></div>
# <script src="http://localhost:5006/autoload.js?bokeh-autoload-element=myplot&bokeh-app-path=/app&bokeh-absolute-url=http://localhost:5006/app"></script>

# The handler processes GET requests with query parameters:
# - bokeh-autoload-element: ID of the target DOM element
# - bokeh-app-path: Path to the Bokeh application (default: '/')
# - bokeh-absolute-url: Absolute URL for resource resolution (optional)

Best Practices

  • This handler should be registered with Tornado's URL routing system, not instantiated directly by users
  • Always provide the 'bokeh-autoload-element' query parameter when requesting the autoload script, or a 400 error will be returned
  • Use 'bokeh-absolute-url' parameter when the application needs to resolve resources from a specific server URL
  • The handler manages document state via state.curdoc - ensure proper cleanup in finally blocks to prevent state leakage
  • Session management is handled via the SessionPrefixHandler mixin's context manager (_session_prefix())
  • The handler is async and should be used in an async Tornado application context
  • Content-Type is automatically set to 'application/javascript' for proper browser handling
  • The generated JavaScript should be included in HTML pages via <script> tags with appropriate query parameters

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function autoload_js_script 75.3% similar

    Generates JavaScript code for autoloading a Bokeh document into a web page element, bundling necessary resources and creating render items for embedding.

    From: /tf/active/vicechatdev/patches/server.py
  • class DocHandler 68.2% similar

    DocHandler is a Tornado request handler that serves HTML pages for Bokeh sessions, combining session management with document rendering capabilities.

    From: /tf/active/vicechatdev/patches/server.py
  • class RootHandler 60.1% similar

    A custom Tornado request handler that extends Bokeh's RootHandler to handle root URL requests with authentication and conditional redirection based on index file extensions.

    From: /tf/active/vicechatdev/patches/server.py
  • function create_static_handler 60.0% similar

    Creates a Tornado route handler tuple for serving static files in a Bokeh/Panel web application, with special handling for root path routing.

    From: /tf/active/vicechatdev/patches/server.py
  • class SessionPrefixHandler 58.6% similar

    A mixin class that provides a context manager for temporarily modifying URL prefix-related state variables during request handling in a Bokeh server application.

    From: /tf/active/vicechatdev/patches/server.py
← Back to Browse