🔍 Code Extractor

class ProxyFallbackHandler

Maturity: 47

A Tornado RequestHandler that wraps another HTTP server callback and proxies requests by modifying the request path before delegating to a fallback handler.

File:
/tf/active/vicechatdev/patches/server.py
Lines:
536 - 550
Complexity:
simple

Purpose

ProxyFallbackHandler serves as a proxy layer in a Tornado web application, intercepting requests and optionally stripping a proxy prefix from the request path before forwarding the request to a fallback handler. This is useful for mounting applications at different URL paths or creating reverse proxy scenarios where path rewriting is needed.

Source Code

class ProxyFallbackHandler(RequestHandler):
    """A `RequestHandler` that wraps another HTTP server callback and
    proxies the subpath.
    """

    def initialize(self, fallback, proxy=None):
        self.fallback = fallback
        self.proxy = proxy

    def prepare(self):
        if self.proxy:
            self.request.path = self.request.path.replace(self.proxy, '')
        self.fallback(self.request)
        self._finished = True
        self.on_finish()

Parameters

Name Type Default Kind
bases RequestHandler -

Parameter Details

fallback: A callable (typically another RequestHandler or HTTP server callback) that will handle the request after path modification. This is the actual handler that processes the request.

proxy: Optional string representing the URL prefix to strip from the request path. If provided, this prefix will be removed from request.path before passing to the fallback handler. If None, no path modification occurs.

Return Value

The class instantiation returns a ProxyFallbackHandler instance. The class itself doesn't return values from its methods (initialize and prepare return None implicitly). The prepare method modifies request state and delegates to the fallback handler, marking the request as finished.

Class Interface

Methods

initialize(self, fallback, proxy=None) -> None

Purpose: Initializes the handler with a fallback handler and optional proxy prefix. Called automatically by Tornado when the handler is instantiated for a request.

Parameters:

  • fallback: A callable that will handle the request after path modification
  • proxy: Optional string prefix to strip from request.path before delegating to fallback

Returns: None

prepare(self) -> None

Purpose: Prepares the request by optionally modifying the path, delegating to the fallback handler, and marking the request as finished. Called automatically by Tornado before the HTTP method handler.

Returns: None

Attributes

Name Type Description Scope
fallback callable The fallback handler callable that processes the request after path modification instance
proxy str or None The URL prefix to strip from request.path before delegating to the fallback handler instance
_finished bool Internal Tornado flag indicating the request has been finished (inherited from RequestHandler, set to True in prepare) instance
request tornado.httputil.HTTPServerRequest The HTTP request object being handled (inherited from RequestHandler) instance

Dependencies

  • tornado

Required Imports

from tornado.web import RequestHandler

Usage Example

from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop

# Define a fallback handler
def my_fallback_handler(request):
    # Process the request
    print(f"Handling request for path: {request.path}")

# Create Tornado application with ProxyFallbackHandler
app = Application([
    (r'/api/.*', ProxyFallbackHandler, {
        'fallback': my_fallback_handler,
        'proxy': '/api'
    })
])

# Start the server
app.listen(8888)
IOLoop.current().start()

# When a request comes to /api/users, the handler will:
# 1. Strip '/api' from the path, making it '/users'
# 2. Pass the modified request to my_fallback_handler

Best Practices

  • Always provide a valid fallback handler callable that can process the modified request
  • Ensure the proxy prefix matches the URL pattern where this handler is registered
  • The handler automatically marks the request as finished (_finished = True) and calls on_finish(), so the fallback should not attempt to finish the request again
  • The prepare() method is called automatically by Tornado before handling the request - do not call it manually
  • This handler is designed for one-time request delegation; it's not suitable for streaming or long-lived connections
  • The fallback handler receives the raw request object, not the ProxyFallbackHandler instance
  • Path modification is simple string replacement - ensure proxy prefix doesn't create ambiguous paths

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class RootHandler 57.5% 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 SessionPrefixHandler 53.1% 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
  • function create_static_handler 51.3% 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 DocHandler 48.8% 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 AutoloadJsHandler 45.0% 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
← Back to Browse