CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-livereload

Python LiveReload server that automatically reloads web pages when source files change

Pending
Overview
Eval results
Files

server.mddocs/

Server Management

Core server functionality for running LiveReload development servers with HTTP serving, WebSocket communication, and file watching integration.

Capabilities

Server Initialization

Create server instances with optional WSGI application integration and custom file watcher configuration.

class Server:
    def __init__(self, app=None, watcher=None):
        """
        Initialize LiveReload server.

        Args:
            app: WSGI application to serve (optional, serves static files if None)
            watcher: Custom Watcher instance (optional, auto-detects best available)
        """

Usage Examples:

# Basic static file server
server = Server()

# Server with WSGI application (Flask, Django, etc.)
from myapp import app
server = Server(app)

# Server with custom watcher
from livereload.watcher import get_watcher_class
CustomWatcher = get_watcher_class()
watcher = CustomWatcher()
server = Server(watcher=watcher)

HTTP Serving Configuration

Start the development server with comprehensive configuration options for ports, hostnames, and development features.

def serve(self, port=5500, liveport=None, host=None, root=None, debug=None, 
          open_url=False, restart_delay=2, open_url_delay=None, 
          live_css=True, default_filename='index.html'):
    """
    Start serving the server with given configuration.

    Args:
        port (int): HTTP server port (default: 5500)
        liveport (int): LiveReload WebSocket port (optional, auto-assigned)
        host (str): Server hostname (default: '127.0.0.1')
        root (str): Static file root directory (optional)
        debug (bool): Enable debug mode with auto-reloading (optional)
        open_url (bool): Automatically open browser (default: False)
        restart_delay (int): Delay before restart in seconds (default: 2)
        open_url_delay (float): Delay before opening browser in seconds (optional)
        live_css (bool): Enable live CSS reloading (default: True)
        default_filename (str): Default file to serve (default: 'index.html')
    """

Usage Examples:

# Basic serving
server.serve()

# Custom port and host
server.serve(port=8080, host='0.0.0.0')

# Development mode with auto-open browser
server.serve(open_url_delay=2, debug=True)

# Custom static root with specific default file
server.serve(root='/path/to/static', default_filename='home.html')

# Production-like serving (no debug, no live CSS)
server.serve(debug=False, live_css=False)

File Watching Registration

Register files, directories, or glob patterns for monitoring with optional callback functions and custom delays.

def watch(self, filepath, func=None, delay=None, ignore=None):
    """
    Add filepath to watcher list.

    Args:
        filepath (str): File path, directory path, or glob pattern to watch
        func (callable): Callback function when changes detected (optional)
        delay (float): Reload delay in seconds (optional)
        ignore (callable): Function to determine ignored files (optional)
    """

Usage Examples:

# Watch current directory
server.watch('.')

# Watch specific files
server.watch('index.html')
server.watch('styles/main.css')

# Watch with glob patterns
server.watch('templates/*.html')
server.watch('**/*.py')

# Watch with callback function
def rebuild():
    print("Rebuilding project...")
    # Custom build logic here

server.watch('src/', rebuild)

# Watch with shell command callback
server.watch('styles/*.less', shell('lessc styles/main.less styles/main.css'))

# Watch with custom delay and ignore function
def ignore_temp_files(filename):
    return filename.endswith('.tmp')

server.watch('project/', delay=1.0, ignore=ignore_temp_files)

HTTP Header Configuration

Add or override HTTP headers for all server responses.

def setHeader(self, name, value):
    """
    Add or override HTTP headers at request start.

    Args:
        name (str): Header field name
        value (str): Header field value
    """

Usage Examples:

# Add CORS headers
server.setHeader('Access-Control-Allow-Origin', '*')
server.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')

# Add caching headers
server.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')

# Add custom headers
server.setHeader('X-Development-Server', 'LiveReload/2.7.1')

Shell Command Integration

Execute shell commands as file change callbacks with support for build tools, preprocessors, and development workflows.

def shell(cmd, output=None, mode='w', cwd=None, shell=False):
    """
    Execute a shell command as a file watcher callback.

    Args:
        cmd (str or list): Shell command to execute
        output (str): Output file path (optional, defaults to devnull)
        mode (str): File write mode for output (default: 'w')
        cwd (str): Working directory for command execution (optional)
        shell (bool): Use shell for command execution (default: False)

    Returns:
        callable: Function that can be used as a watcher callback
    """

Usage Examples:

# Compile LESS to CSS
server.watch('styles/*.less', shell('lessc styles/main.less styles/main.css'))

# Compile TypeScript
server.watch('src/*.ts', shell('tsc', output='dist/bundle.js'))

# Run tests on Python file changes
server.watch('tests/*.py', shell(['python', '-m', 'pytest', 'tests/']))

# Custom build script with working directory
server.watch('package.json', shell('./build.sh', cwd='/path/to/project'))

# Complex command with shell features
server.watch('docs/*.md', shell('pandoc docs/*.md -o dist/docs.html', shell=True))

WSGI Application Integration

Integration with WSGI applications for full-stack development with live reloading.

Usage Examples:

# Flask integration
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

server = Server(app)
server.watch('templates/')
server.watch('static/')
server.serve()

# Django integration (alternative to management command)
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = get_wsgi_application()

server = Server(app)
server.watch('myapp/templates/')
server.watch('myapp/static/')
server.serve(port=8000)

Advanced Usage

Custom Development Workflows

# Multi-step build process
def build_assets():
    # Compile SASS
    subprocess.run(['sass', 'scss/main.scss', 'static/css/main.css'])
    # Optimize images
    subprocess.run(['imagemin', 'images/*', '--out-dir=static/images/'])
    # Bundle JavaScript
    subprocess.run(['webpack', '--mode=development'])

server = Server()
server.watch('scss/', build_assets)
server.watch('images/', build_assets)  
server.watch('js/', build_assets)
server.serve(port=3000, open_url_delay=1)

Production-Ready Development Server

server = Server()
server.setHeader('X-Frame-Options', 'DENY')
server.setHeader('X-Content-Type-Options', 'nosniff')
server.setHeader('X-XSS-Protection', '1; mode=block')

# Watch only specific file types
server.watch('**/*.html')
server.watch('**/*.css')
server.watch('**/*.js')

server.serve(
    host='0.0.0.0',  # Allow external connections
    port=8080,
    debug=False,     # Disable debug mode
    live_css=True,   # Keep CSS live reloading
    restart_delay=1   # Faster restarts
)

Handler Classes (Advanced)

Internal handler classes for advanced customization and integration with Tornado web framework.

class LiveReloadHandler(WebSocketHandler):
    """
    WebSocket handler for browser-server communication.
    
    Manages client connections and broadcasts reload notifications.
    """
    
    def check_origin(self, origin):
        """Allow cross-origin WebSocket connections."""
        return True
    
    def on_close(self):
        """Handle client disconnection."""
        pass
    
    def send_message(self, message):
        """Send message to connected client."""
        pass

class StaticFileHandler(MtimeStaticFileHandler):
    """
    Enhanced static file handler with modification time support.
    
    Extends Tornado's StaticFileHandler with custom headers and caching.
    """
    
    def set_default_headers(self):
        """Set default HTTP headers for all responses."""
        pass

class LiveReloadJSHandler(RequestHandler):
    """Handler serving the LiveReload JavaScript client."""
    
    def get(self):
        """Serve livereload.js client script."""
        pass

class ForceReloadHandler(RequestHandler):
    """Handler for triggering manual page reloads."""
    
    def post(self):
        """Force reload all connected clients."""
        pass

Advanced Handler Usage:

from livereload.handlers import LiveReloadHandler, StaticFileHandler
from tornado import web

# Custom application with LiveReload handlers
app = web.Application([
    (r'/livereload', LiveReloadHandler),
    (r'/static/(.*)', StaticFileHandler, {'path': './static'}),
])

# Custom handler setup
LiveReloadHandler.watcher = watcher
LiveReloadHandler.live_css = True

Install with Tessl CLI

npx tessl i tessl/pypi-livereload

docs

cli-and-integrations.md

file-watching.md

index.md

server.md

tile.json