🔍 Code Extractor

function serve

Maturity: 70

Serves one or more Panel objects on a single web server, allowing interactive dashboards and applications to be deployed locally or remotely with configurable networking and threading options.

File:
/tf/active/vicechatdev/patches/server.py
Lines:
471 - 533
Complexity:
moderate

Purpose

This function is the primary entry point for deploying Panel applications. It creates and starts a web server that hosts Panel objects (interactive visualizations, dashboards, or applications). It supports serving multiple apps at different URL slugs, customizing server configuration (port, address, websocket origins), and running in threaded or non-threaded mode. The function handles both simple single-panel deployments and complex multi-app scenarios with custom routing.

Source Code

def serve(panels, port=0, address=None, websocket_origin=None, loop=None,
          show=True, start=True, title=None, verbose=True, location=True,
          threaded=False, **kwargs):
    """
    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.

    Arguments
    ---------
    panel: 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
    address : str
      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.
    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())
      The tornado IOLoop to run the Server on
    show : boolean (optional, default=True)
      Whether to open the server in a new browser tab on start
    start : boolean(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
    location : boolean 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
    kwargs: dict
      Additional keyword arguments to pass to Server instance
    """
    kwargs = dict(kwargs, **dict(
        port=port, address=address, websocket_origin=websocket_origin,
        loop=loop, show=show, start=start, title=title, verbose=verbose,
        location=location
    ))
    if threaded:
        from tornado.ioloop import IOLoop
        kwargs['loop'] = loop = IOLoop() if loop is None else loop
        server = StoppableThread(
            target=get_server, io_loop=loop, args=(panels,), kwargs=kwargs
        )
        server_id = kwargs.get('server_id', uuid.uuid4().hex)
        state._threads[server_id] = server
        server.start()
    else:
        server = get_server(panels, **kwargs)
    return server

Parameters

Name Type Default Kind
panels - - positional_or_keyword
port - 0 positional_or_keyword
address - None positional_or_keyword
websocket_origin - None positional_or_keyword
loop - None positional_or_keyword
show - True positional_or_keyword
start - True positional_or_keyword
title - None positional_or_keyword
verbose - True positional_or_keyword
location - True positional_or_keyword
threaded - False positional_or_keyword
**kwargs - - var_keyword

Parameter Details

panels: The Panel object(s) to serve. Can be: (1) a single Panel/Viewable object, (2) a function that returns a Panel object (called for each session), or (3) a dictionary mapping URL slugs (strings) to Panel objects or functions. Example: {'app1': my_panel, 'app2': my_function}

port: The TCP port number for the server to listen on. Default is 0, which automatically selects an available port. Common values are 5006, 8000, or any valid port number (1-65535)

address: The network address/interface the server should bind to. None uses default (typically localhost). Use '0.0.0.0' to listen on all network interfaces, or specify a specific IP address

websocket_origin: Host(s) allowed to connect to the websocket. Can be a string or list of strings. Required when embedding the app in external websites. If None, defaults to 'localhost'. Example: ['example.com', 'www.example.com']

loop: A Tornado IOLoop instance to run the server on. If None, uses IOLoop.current(). Useful for integrating with existing Tornado applications or custom event loops

show: If True, automatically opens the served application in a new browser tab when the server starts. Set to False for headless deployments or when running in non-interactive environments

start: If True, starts the server immediately. If False, returns the server object without starting it, allowing manual control via server.start()

title: HTML title for the application. Can be a string (applied to all apps) or a dictionary mapping URL slugs to titles. Example: {'app1': 'Dashboard 1', 'app2': 'Dashboard 2'}

verbose: If True, prints the server address and port to stdout when starting. Useful for debugging and knowing where to access the application

location: Controls URL location tracking. If True, creates a Location component to observe and modify the URL. If False, disables location tracking. Can also accept a panel.io.location.Location instance for custom configuration

threaded: If True, starts the server on a separate thread, allowing the main thread to continue execution. If False, runs the server on the current thread (blocking). Useful for running servers in background or in Jupyter notebooks

kwargs: Additional keyword arguments passed directly to the underlying Server instance. Can include advanced Bokeh server configuration options like 'allow_websocket_origin', 'num_procs', 'check_unused_sessions', etc.

Return Value

Returns a server object. If threaded=False, returns a Bokeh Server instance that can be controlled with methods like .stop(). If threaded=True, returns a StoppableThread instance containing the server, which can be stopped with .stop() and joined with .join(). The server object provides access to the running server's configuration and state.

Dependencies

  • panel
  • bokeh
  • tornado
  • param
  • uuid
  • threading

Required Imports

from panel.io import serve

Conditional/Optional Imports

These imports are only needed under specific conditions:

from tornado.ioloop import IOLoop

Condition: only when threaded=True to create a new IOLoop for the thread

Required (conditional)

Usage Example

import panel as pn
from panel.io import serve

# Example 1: Serve a single panel
panel_obj = pn.pane.Markdown('# Hello World')
server = serve(panel_obj, port=5006, show=True)

# Example 2: Serve multiple apps at different URLs
def create_app1():
    return pn.Column('# App 1', pn.widgets.Button(name='Click'))

def create_app2():
    return pn.Column('# App 2', pn.widgets.TextInput(name='Input'))

apps = {
    'dashboard': create_app1,
    'form': create_app2
}
server = serve(apps, port=8000, title={'dashboard': 'Dashboard', 'form': 'Form'})

# Example 3: Serve in threaded mode (non-blocking)
server = serve(panel_obj, port=5007, threaded=True, show=False)
print('Server running in background')
# Do other work here
server.stop()  # Stop when done

# Example 4: Serve with custom websocket origins for embedding
server = serve(
    panel_obj,
    port=5008,
    websocket_origin=['example.com', 'www.example.com'],
    address='0.0.0.0'
)

Best Practices

  • Use threaded=True when serving from Jupyter notebooks or when you need the main thread to remain responsive
  • Always specify websocket_origin when embedding Panel apps in external websites to avoid CORS issues
  • Use port=0 for automatic port selection in development, but specify explicit ports in production
  • When serving multiple apps, use descriptive URL slugs that clearly indicate the app's purpose
  • Set show=False in production environments or automated deployments to prevent browser windows from opening
  • Use functions instead of Panel objects when you need separate sessions for each user (functions are called per session)
  • For production deployments, consider using a reverse proxy (nginx, Apache) in front of the Panel server
  • Set verbose=True during development for easy debugging, but consider False in production logs
  • When using address='0.0.0.0', ensure proper firewall and security configurations are in place
  • Store the returned server object if you need to programmatically stop the server later

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_server 84.3% similar

    Creates and configures a Bokeh Server instance to serve Panel applications with support for OAuth authentication, static file serving, and session management.

    From: /tf/active/vicechatdev/patches/server.py
  • function main_v21 55.8% similar

    Entry point function that initializes and serves the CDocs Panel web application with configurable port and debug mode options.

    From: /tf/active/vicechatdev/cdocs_panel_app.py
  • function _eval_panel 54.3% similar

    Evaluates and initializes a panel component (function, template, or panel object) within a Bokeh document context, handling different panel types and modifying the document accordingly.

    From: /tf/active/vicechatdev/patches/server.py
  • class Application 50.9% similar

    A custom Bokeh Application subclass that extends BkApplication to integrate with Panel's state management system, handling session creation callbacks and document initialization with templates.

    From: /tf/active/vicechatdev/patches/server.py
  • function init_doc 48.8% similar

    Initializes a Bokeh document by registering session information and setting up document lifecycle event handlers for Panel applications.

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