🔍 Code Extractor

class SessionPrefixHandler

Maturity: 34

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

File:
/tf/active/vicechatdev/patches/server.py
Lines:
181 - 206
Complexity:
moderate

Purpose

SessionPrefixHandler is designed to be mixed into Tornado request handler classes in a Bokeh server context. It manages the base_url and rel_path state variables during request processing, ensuring proper URL resolution for embedded Bokeh applications. The class handles both regular requests and autoload.js requests with absolute URLs, temporarily setting appropriate URL prefixes and restoring them after the request completes.

Source Code

class SessionPrefixHandler:

    @contextmanager
    def _session_prefix(self):
        prefix = self.request.uri.replace(self.application_context._url, '')
        if not prefix.endswith('/'):
            prefix += '/'
        base_url = urljoin('/', prefix)
        rel_path = '/'.join(['..'] * self.application_context._url.strip('/').count('/'))
        old_url, old_rel = state.base_url, state.rel_path

        # Handle autoload.js absolute paths
        abs_url = self.get_argument('bokeh-absolute-url', default=None)
        if abs_url is not None:
            app_path = self.get_argument('bokeh-app-path', default=None)
            rel_path = abs_url.replace(app_path, '')

        with edit_readonly(state):
            state.base_url = base_url
            state.rel_path = rel_path
        try:
            yield
        finally:
            with edit_readonly(state):
                state.base_url = old_url
                state.rel_path = old_rel

Parameters

Name Type Default Kind
bases - -

Parameter Details

bases: Base classes to inherit from when creating the SessionPrefixHandler class. This parameter is used during class creation but not during instantiation.

Return Value

The class itself returns nothing on instantiation. The _session_prefix method is a context manager that yields control to the caller while temporarily modifying state variables, then restores them on exit. It does not return a specific value.

Class Interface

Methods

_session_prefix(self) -> ContextManager

Purpose: Context manager that temporarily modifies global state variables (base_url and rel_path) based on the current request URI and application context, then restores them on exit

Returns: A context manager that yields control while state is modified, automatically restoring original values on exit

Attributes

Name Type Description Scope
request tornado.httputil.HTTPServerRequest The current HTTP request object, expected to be provided by the Tornado RequestHandler base class. Used to access request.uri for prefix calculation instance
application_context object An object containing application context information, specifically expected to have a '_url' attribute representing the application's base URL path instance

Dependencies

  • tornado
  • bokeh
  • param

Required Imports

from contextlib import contextmanager
from urllib.parse import urljoin
from util import edit_readonly
from state import state

Usage Example

from tornado.web import RequestHandler
from contextlib import contextmanager
from urllib.parse import urljoin

# Assuming state and edit_readonly are available
class MyBokehHandler(SessionPrefixHandler, RequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.application_context = type('obj', (object,), {'_url': '/app'})
    
    def get(self):
        # Use the session prefix context manager
        with self._session_prefix():
            # Code here runs with modified state.base_url and state.rel_path
            self.write(f"Base URL: {state.base_url}")
            self.write(f"Relative path: {state.rel_path}")
        # State is automatically restored after exiting the context

Best Practices

  • This class is intended to be used as a mixin with Tornado RequestHandler subclasses, not instantiated directly
  • Always use _session_prefix as a context manager (with statement) to ensure state is properly restored
  • The class expects the handler to have 'request' and 'application_context' attributes available
  • State modifications are temporary and automatically restored when exiting the context
  • The method handles special cases for autoload.js requests by checking for 'bokeh-absolute-url' and 'bokeh-app-path' query parameters
  • Ensure the global 'state' object is properly initialized before using this mixin
  • The edit_readonly context manager is required to modify read-only state attributes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class DocHandler 63.1% 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 62.4% 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
  • class AutoloadJsHandler 58.6% similar

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

    From: /tf/active/vicechatdev/patches/server.py
  • function create_static_handler 53.9% 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
  • function _initialize_session_info 53.7% similar

    Initializes and manages session information for a web application session, tracking session lifecycle timestamps and user agent data while maintaining a configurable history limit.

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