### Basic Server Usage Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md This example demonstrates how to start the LiveReload server with custom configurations for port, host, root directory, and browser opening delay. It requires the Server class to be imported. ```python from livereload import Server server = Server() server.serve( port=8080, host='0.0.0.0', root='./dist', open_url_delay=2, default_filename='index.html' ) ``` -------------------------------- ### Complex Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/cli.md A comprehensive example combining serving from a directory, watching a specific source, applying a reload delay, automatically opening the browser, and enabling debug logging. ```bash $ livereload build/ --target src/ --wait 1.5 -o 3 --debug # Serves from build/ directory # Watches src/ for changes # Waits 1.5 seconds before reload (time for build) # Opens browser after 3 seconds # Shows debug logging output ``` -------------------------------- ### Start server and serve files Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Starts the livereload server to begin watching files and serving content. This should typically be the last call in your configuration. ```python server.serve() ``` -------------------------------- ### server.serve() Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md Starts the LiveReload server and begins watching registered files. Blocks indefinitely until KeyboardInterrupt. ```APIDOC ## serve() ### Description Starts the LiveReload server and begins watching registered files. Blocks indefinitely until KeyboardInterrupt. ### Method Not applicable (Python method call) ### Endpoint Not applicable (Python method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **port** (int) - Optional - Port for main server. Default: 5500 - **liveport** (int or None) - Optional - Separate port for WebSocket livereload endpoint. Default: None - **host** (str or None) - Optional - Hostname to bind to. Use '0.0.0.0' for external access. Default: '127.0.0.1' - **root** (str or None) - Optional - Root directory for static file serving. Sets `self.root` if provided. Default: None - **debug** (bool or None) - Optional - Enable Tornado debug mode. Auto-determined if None. Default: None - **open_url** (bool) - Optional - Deprecated. Use `open_url_delay` instead. Default: False - **restart_delay** (float) - Optional - Seconds to wait before reloading after file changes. Default: 2 - **open_url_delay** (float or None) - Optional - If set, opens browser window after this many seconds. Spawns background thread. Default: None - **live_css** (bool) - Optional - Enable smart CSS reloading without full page reload. Default: True - **default_filename** (str) - Optional - Default file served when directory is requested. Default: 'index.html' ### Request Example ```python from livereload import Server server = Server() server.serve( port=8080, host='0.0.0.0', root='./dist', open_url_delay=2, default_filename='index.html' ) ``` ### Response #### Success Response (None specific, blocks indefinitely) This method blocks indefinitely until KeyboardInterrupt. #### Response Example None ``` -------------------------------- ### Start LiveReload Django Server Source: https://github.com/lepture/python-livereload/blob/master/docs/integrations/django.md Run the livereload management command to start the Django server with live-reloading capabilities. ```bash python ./manage.py livereload ``` -------------------------------- ### start() Method Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Initializes the asynchronous notifier and integrates it with the Tornado IOLoop. This method prepares the watcher to handle events asynchronously. ```APIDOC ## start(callback) ### Description Initializes the async notifier and integrates it with the Tornado IOLoop. This prepares the watcher to handle file system events asynchronously. ### Parameters - **callback** (callable): The function to be called when file system events are detected. ### Returns - **bool**: True if the notifier was successfully initialized, False otherwise. ### Behavior 1. Returns early if the notifier is already initialized (notifier exists). 2. Stores the provided callback function. 3. Creates a TornadoAsyncNotifier integrated with `IOLoop.instance()`. 4. Calls the provided callback function immediately to ensure initialization. 5. Returns True upon successful initialization. ``` -------------------------------- ### livereload.cli.main Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/modules.md Entry point for the livereload CLI command. It parses arguments and starts the livereload server. ```APIDOC ## livereload.cli.main ### Description Entry point for the livereload CLI command. It parses arguments and starts the livereload server. ### Method Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### start_tasks() Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Class method to initialize file watching. It ensures watching is started only once and sets up the watcher. ```APIDOC ## start_tasks() ### Description Initializes file watching if not already started. Called once when the first client connects. ### Behavior - Returns early if already started (checks _last_reload_time) - If no tasks registered, watches current working directory - Sets _last_reload_time timestamp - Calls watcher.start() with poll_tasks callback - Falls back to PeriodicCallback (800ms polling) if watcher.start() returns False ### Signature ```python @classmethod start_tasks(cls) ``` ``` -------------------------------- ### Multiple Watchers Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Set up multiple watchers to monitor different file types or directories and trigger corresponding build commands. ```python server.watch('less/', shell('lessc...')) server.watch('ts/', shell('tsc...')) server.watch('html/') ``` -------------------------------- ### Start LiveReload Server with Django Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Run this command to start the LiveReload server alongside the Django development server. It defaults to 127.0.0.1:8000. ```bash python manage.py livereload ``` -------------------------------- ### Start File Watching Tasks Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Initializes file watching if it hasn't started yet, typically called when the first client connects. Falls back to periodic polling if direct watcher start fails. ```python @classmethod start_tasks(cls) ``` -------------------------------- ### Bottle Basic Setup Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Set up LiveReload with a Bottle application. Watch for changes in the 'views/' directory and serve on port 8080. ```python from bottle import Bottle from livereload import Server app = Bottle() @app.route('/') def index(): return 'Hello World' if __name__ == '__main__': server = Server(app) server.watch('views/') server.serve(port=8080) ``` -------------------------------- ### Combined LiveReload CLI Options Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Example demonstrating the use of multiple command-line arguments simultaneously for comprehensive configuration. ```bash $ livereload ./build --target ./src --host 0.0.0.0 -p 5500 --wait 1.5 -o 2 -d ``` -------------------------------- ### Livereload Console Script Entry Point Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/modules.md This is how livereload is installed as a command-line tool via setuptools entry_points. ```python entry_points={ 'console_scripts': [ 'livereload = livereload.cli:main', ] } ``` -------------------------------- ### Start INotifyWatcher with Tornado IOLoop Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Initializes the asynchronous notifier and integrates it with the Tornado IOLoop. The provided callback is executed immediately upon initialization. Returns True if the notifier was successfully initialized, False otherwise. Avoids re-initialization if already started. ```python start(callback) ``` -------------------------------- ### Bottle.py Server Setup with LiveReload Source: https://github.com/lepture/python-livereload/blob/master/docs/integrations/bottle.md This snippet demonstrates how to initialize and run a bottle.py application with LiveReload. Ensure bottle.debug(True) is called for template reloading. ```python import bottle from livereload import Server bottle.debug(True) # debug mode is required for templates to be reloaded app = Bottle() server = Server(app) server.watch(...) server.serve() ``` -------------------------------- ### CLI Serve Current Directory Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Start the livereload server to serve the current directory. This is the most basic CLI usage. ```bash # Serve current directory live-reload ``` -------------------------------- ### Start Standalone Static File Server Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/overview.md Use this snippet to start a standalone development server that serves static files from the current directory and automatically reloads the browser on file changes. The server listens on port 5500 by default. ```python from livereload import Server server = Server() server.serve(port=5500, root='.') ``` -------------------------------- ### Install LiveReload using pip Source: https://github.com/lepture/python-livereload/blob/master/README.md Install the LiveReload package using pip. This command is typically run in your terminal. ```bash $ pip install livereload ``` -------------------------------- ### Livereload CLI Help Source: https://github.com/lepture/python-livereload/blob/master/docs/cli.md Displays the help message for the livereload command, outlining its usage and available options for starting a live-reloading server. ```text $ livereload --help usage: livereload [-h] [--host HOST] [-p PORT] [-t TARGET] [-w WAIT] [-o OPEN_URL_DELAY] [-d] [directory] Start a `livereload` server positional arguments: directory Directory to serve files from options: -h, --help show this help message and exit --host HOST Hostname to run `livereload` server on -p PORT, --port PORT Port to run `livereload` server on -t TARGET, --target TARGET File or directory to watch for changes -w WAIT, --wait WAIT Time delay in seconds before reloading -o OPEN_URL_DELAY, --open-url-delay OPEN_URL_DELAY If set, triggers browser opening seconds after starting -d, --debug Enable Tornado pretty logging ``` -------------------------------- ### ObjectDict Usage Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/types.md Demonstrates creating and accessing attributes of an ObjectDict. Useful for dictionary-like objects that benefit from attribute-style access. ```python from tornado.util import ObjectDict msg = ObjectDict({'command': 'hello'}) print(msg.command) # 'hello' ``` -------------------------------- ### CLI Usage Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Provides common command-line interface commands for starting and configuring the livereload server. ```APIDOC ## CLI Usage ### Description Command-line interface for starting and managing the livereload server. ### Examples - **Serve current directory:** `livereload` - **Custom port:** `livereload -p 8000` - **Watch different directory:** `livereload ./dist --target ./src` - **Auto-open browser:** `livereload -o 2` ``` -------------------------------- ### Comprehensive Development Server Setup with LiveReload Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/examples.md Sets up a development server that watches multiple file patterns, triggers build tasks (npm scripts), and serves static assets. Includes CORS headers for API testing. ```python #!/usr/bin/env python """Development server with LiveReload""" from livereload import Server, shell import os def create_dev_server(): # Create Server server = Server() # Configuration root_dir = 'dist' port = 8000 # Ensure build directory exists os.makedirs(root_dir, exist_ok=True) # Watch patterns tasks = [ ('src/js/**/*.js', shell('npm run build:js'), 'JavaScript build'), ('src/css/**/*.scss', shell('npm run build:css'), 'SASS compilation'), ('src/html/**/*.html', shell('npm run build:html'), 'HTML copy'), ('static/', None, 'Static assets'), ] for pattern, cmd, description in tasks: print(f'Watching: {description}') server.watch(pattern, cmd) # Add CORS headers for API testing server.setHeader('Access-Control-Allow-Origin', '*') server.setHeader('Cache-Control', 'no-cache') return server if __name__ == '__main__': server = create_dev_server() print('\n' + '='*50) print('Development Server Started') print('='*50) print(f'http://localhost:8000') print('Press Ctrl+C to stop') print('='*50 + '\n') server.serve( root='dist', port=8000, host='127.0.0.1', debug=False, # Don't auto-reload Python open_url_delay=2, live_css=True, default_filename='index.html' ) ``` -------------------------------- ### Flask App Setup with LiveReload Source: https://github.com/lepture/python-livereload/blob/master/docs/integrations/flask.md Use `livereload.Server` to serve a Flask application. Ensure Flask's debug mode is enabled for template reloading. ```python from livereload import Server app = create_app() app.debug = True # debug mode is required for templates to be reloaded server = Server(app.wsgi_app) server.watch(...) server.serve() ``` -------------------------------- ### Serve Livereload Server with Full Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Configures the livereload server with specific ports, host, static file root, and live reload settings. This example sets a custom port, binds to all interfaces, specifies a distribution directory for static files, uses the standard LiveReload port, and enables automatic browser opening after a delay. ```python from livereload import Server server = Server() server.serve( port=8080, host='0.0.0.0', root='./dist', liveport=35729, # Standard LiveReload port open_url_delay=2, # Open browser after 2 seconds live_css=True, # Smart CSS reload default_filename='index.html', debug=False # Disable Tornado auto-reload in production ) ``` -------------------------------- ### Minimal LiveReload Server Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Start a basic LiveReload server. This server will watch for file changes and reload the browser automatically. ```python from livereload import Server server = Server() server.serve() ``` -------------------------------- ### Serve Livereload Server with Minimal Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Starts the livereload server with default settings. The server will run on the default port (5500) and bind to the default host ('127.0.0.1'). ```python from livereload import Server # Minimal setup server = Server() server.serve() ``` -------------------------------- ### INotifyWatcher Constructor Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Initializes the INotifyWatcher. It sets up the pyinotify WatchManager and prepares for event handling. Requires the pyinotify package to be installed. ```APIDOC ## INotifyWatcher() ### Description Initializes watcher with pyinotify WatchManager and prepares for event handling. ### Parameters This method does not take any explicit parameters. ### Attributes - **wm** (WatchManager): Manager for inotify watches. - **notifier** (AsyncNotifier or None): Async notifier integrated with Tornado IOLoop. - **callback** (callable or None): Function called on file system events. ### Requirements - pyinotify package installed ``` -------------------------------- ### Development Server Sync to Staging Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/examples.md This example sets up Livereload to watch source files, trigger a build, and then sync the compiled output to a staging server using rsync. It includes a delay to ensure the build completes before syncing. ```python import subprocess from livereload import Server, shell def sync_to_staging(): subprocess.run(['rsync', '-az', 'dist/', 'staging:/var/www/app/']) print('Synced to staging server') server = Server() # Compile and build server.watch('src/', shell('npm run build')) # After build, sync to staging (with delay for build to finish) server.watch('dist/', sync_to_staging, delay=2) server.serve(root='dist/', port=8000) ``` -------------------------------- ### Open Browser Automatically Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/cli.md Automatically opens the default web browser a specified number of seconds after the server starts. ```bash $ livereload --open-url-delay 2 # Opens browser 2 seconds after starting server ``` -------------------------------- ### CLI Auto-Open Browser Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Start the livereload server and automatically open the default web browser to the served application after a specified delay in seconds. ```bash # Auto-open browser live-reload -o 2 ``` -------------------------------- ### Changes Queue Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/types.md Represents a queue of pending file changes to be processed. Each item is a tuple containing the filename and a timestamp or None. ```python [ ('style.css', None), ('app.py', 2.0), ('__livereload__', 0) ] ``` -------------------------------- ### Configure Django Static Files and WhiteNoise Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Steps to ensure static files are served correctly in Django, including using `collectstatic` and installing WhiteNoise. ```bash python manage.py collectstatic ``` ```bash pip install whitenoise ``` -------------------------------- ### Start LiveReload Django Server on Specific Address and Port Source: https://github.com/lepture/python-livereload/blob/master/docs/integrations/django.md Specify the address and port for the Django server to listen on when using the livereload management command. ```bash python ./manage.py livereload 127.0.0.1:8000 ``` -------------------------------- ### Production Server Configuration (Not Recommended) Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md A production-like configuration for livereload, disabling debugging and live CSS. This setup is not recommended for production environments. ```python server = Server(app.wsgi_app) server.serve( port=80, host='0.0.0.0', debug=False, # No polling live_css=False # Full reload only (safer) ) ``` -------------------------------- ### Generic WSGI Application Integration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Integrate LiveReload with any WSGI-compatible application. This example uses a simple custom WSGI app and watches the current directory. ```python from livereload import Server # Your WSGI application def my_wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Hello World'] server = Server(my_wsgi_app) server.watch('.') # Watch current directory server.serve() ``` -------------------------------- ### Modification Times Dictionary Example Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/types.md Maps file paths to their modification times (seconds since epoch). Used to track file changes. ```python {} '/home/user/project/style.css': 1623456789.123456, '/home/user/project/app.py': 1623456790.654321 } ``` -------------------------------- ### Configure Static Files Serving with WhiteNoise Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md To serve static files efficiently with Django, install WhiteNoise and configure your settings.py to use its middleware and define static file locations. ```python pip install whitenoise ``` ```python MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Add this # ... ] ``` ```python STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] ``` -------------------------------- ### Auto-rebuild and Reload Sphinx Documentation Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/examples.md This example demonstrates how to automatically rebuild Sphinx documentation when source files change and then reload the browser. It's ideal for projects with documentation managed by Sphinx. ```python from livereload import Server, shell import os server = Server() # Watch RST files, rebuild with Sphinx server.watch('docs/source/', shell('sphinx-build -b html docs/source docs/build/html')) # Serve built HTML server.serve( root='docs/build/html', port=8000, open_url_delay=1 ) ``` -------------------------------- ### Get Default Watcher Class Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Automatically selects the best available watcher class based on the operating system and installed dependencies. INotifyWatcher is preferred on Linux for efficiency if pyinotify is installed. ```python from livereload.watcher import get_watcher_class WatcherClass = get_watcher_class() watcher = WatcherClass() ``` -------------------------------- ### Serve livereload.js Client Script Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Handles GET requests to /livereload.js by serving the client-side livereload.js library. Sets the Content-Type header to application/javascript and writes the binary file content directly to the response. ```python def get(self) ``` -------------------------------- ### Create and Configure Server Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Instantiate the Server, optionally with a WSGI app. Configure watches for files or directories and specify actions to take on change. ```python server = Server() server.watch('src/', func) server.setHeader('CORS', '*') server.serve(port=8000, open_url_delay=1) ``` ```python server = Server(app.wsgi_app) server.serve(port=8000, liveport=35729) ``` -------------------------------- ### Configure LiveReload Logger Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md This Python code snippet shows how to get the 'livereload' logger, set its level to DEBUG, and add a StreamHandler to output logs to the console. This is useful for custom logging setups. ```python import logging # Get the logger logger = logging.getLogger('livereload') # Set logging level logger.setLevel(logging.DEBUG) # Add custom handler handler = logging.StreamHandler() logger.addHandler(handler) ``` -------------------------------- ### Initialize Livereload Server Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Demonstrates initializing the `Server` with different configurations. Use static file serving when no WSGI app is provided. Provide a WSGI application for proxying requests. A custom watcher can be supplied for file monitoring. ```python from livereload import Server # Static file serving server = Server() # With WSGI app (Flask) app = create_flask_app() server = Server(app=app.wsgi_app) # Custom watcher from livereload.watcher import Watcher custom_watcher = Watcher() server = Server(watcher=custom_watcher) ``` -------------------------------- ### Initialize Server Class Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Instantiate the Server class. The app and watcher arguments are optional. ```python from livereload import Server server = Server(app=None, watcher=None) ``` -------------------------------- ### Server Integration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/cli.md Demonstrates how the CLI integrates with the `Server` class to set up watching and serving. Static file serving is used by default. ```python server = Server() server.watcher.watch(args.target or args.directory, delay=args.wait) server.serve( host=args.host, port=args.port, root=args.directory, open_url_delay=args.open_url_delay ) ``` -------------------------------- ### Get and Store File Modification Time Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/types.md Demonstrates how to get the current modification time of a file and store it in the watcher's tracking dictionary. ```python mtime = os.path.getmtime(filepath) # Get current mtime watcher._task_mtimes[filepath] = mtime # Store in tracking dict ``` -------------------------------- ### LiveReloadJSHandler Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Handles GET requests to serve the client-side livereload.js library. ```APIDOC ## GET /livereload.js ### Description Serves the client-side livereload.js library. ### Method GET ### Endpoint /livereload.js ### Behavior - Sets Content-Type header to 'application/javascript' - Reads livereload.js from the `livereload/vendors/` directory - Writes binary file content directly to the response. ``` -------------------------------- ### Server Constructor Options Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Options available when initializing the Server class. ```APIDOC ## Server(app=None, watcher=None) ### Description Initializes the Server with optional WSGI application and custom watcher. ### Parameters #### Path Parameters - **app** (WSGI callable or None) - Optional - WSGI application to proxy requests through. If None, static file serving mode is used. - **watcher** (Watcher instance or None) - Optional - Custom watcher instance for file monitoring. If None, automatically selects INotifyWatcher (Linux+pyinotify) or Watcher (polling). ### Request Example ```python from livereload import Server # Static file serving server = Server() # With WSGI app (Flask) app = create_flask_app() server = Server(app=app.wsgi_app) # Custom watcher from livereload.watcher import Watcher custom_watcher = Watcher() server = Server(watcher=custom_watcher) ``` ``` -------------------------------- ### serve() Method Options Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Options available when calling the serve() method on a Server instance. ```APIDOC ## server.serve() ### Description Starts the development server, serving files and watching for changes. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **port** (int) - Optional - Port number for main server. Standard HTTP ports: 8000, 8080, 5000 for development; 80 for production. Default: 5500 - **liveport** (int or None) - Optional - Port for WebSocket /livereload endpoint. If None, uses same port as main server. Separate port useful for splitting concerns or standard LiveReload port 35729. - **host** (str or None) - Optional - Hostname to bind to. Use '127.0.0.1' for local-only access (secure). Use '0.0.0.0' for external access (all interfaces). Use specific IP for partial external access. Default: '127.0.0.1' - **root** (str or None) - Optional - Root directory for static file serving. If None, uses current working directory ('.'). Only used when app=None. - **debug** (bool or None) - Optional - Enable Tornado debug mode with auto-reloading on code changes. Causes CPU-intensive polling. If None: True when app is set, False otherwise. Only set True for development. - **open_url** (bool) - Optional - Deprecated. Use open_url_delay instead. Default: False - **restart_delay** (float) - Optional - Seconds to delay before reloading browser after file changes. Allows build processes to complete. Default: 2 - **open_url_delay** (float or None) - Optional - If set, opens default web browser this many seconds after server starts. Spawns background thread. Useful for auto-launch on development startup. - **live_css** (bool) - Optional - Enable smart CSS reloading. If True, CSS changes reload stylesheets without full page reload. If False, all changes trigger full page reload. Browser must support link reload. Default: True - **default_filename** (str) - Optional - Default filename served when directory is requested. Set to index.php or other for PHP/other frameworks. Default: 'index.html' ### Request Example ```python from livereload import Server # Minimal setup server = Server() server.serve() # Full configuration server = Server() server.serve( port=8080, host='0.0.0.0', root='./dist', liveport=35729, # Standard LiveReload port open_url_delay=2, # Open browser after 2 seconds live_css=True, # Smart CSS reload default_filename='index.html', debug=False # Disable Tornado auto-reload in production ) # Development with auto-reload server.serve( port=5000, debug=True, # Tornado monitors Python files open_url_delay=1 ) # WSGI app configuration from flask import Flask app = Flask(__name__) from livereload import Server server = Server(app.wsgi_app) server.serve( port=5000, debug=True, # Auto-detects True because app is set open_url_delay=2 ) ``` ``` -------------------------------- ### Server Constructor Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md Initializes a new Server instance. It can optionally take a WSGI application and a custom watcher. ```APIDOC ## Server Class **Import:** `from livereload import Server` **Source:** `livereload/server.py:179` ### Constructor ```python Server(app=None, watcher=None) ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | app | WSGI callable or None | No | None | A WSGI application instance to proxy requests through. If None, static file serving is used instead. | | watcher | Watcher instance or None | No | None | Custom watcher instance. If None, automatically selects INotifyWatcher (Linux with pyinotify) or Watcher (polling). | **Source:** `livereload/server.py:193` ``` -------------------------------- ### serve() Method Signature Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md This snippet shows the signature of the serve() method with all its parameters and their default values. It is useful for understanding the available configuration options. ```python server.serve(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') ``` -------------------------------- ### Server Application Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/endpoints.md Configure the main server port, host, debug mode, and live CSS reloading. ```python server.application(port=5500, host='127.0.0.1', liveport=None, debug=True, live_css=True) ``` -------------------------------- ### Get LiveReload Logger Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/modules.md Obtain the logger instance for the 'livereload' module. This is useful for configuring logging levels or emitting messages. ```python logger = logging.getLogger('livereload') ``` -------------------------------- ### Server Constructor Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md Initializes the LiveReload server. Optionally takes a WSGI application to proxy requests or a custom watcher instance. ```python Server(app=None, watcher=None) ``` -------------------------------- ### Django Integration Command Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/overview.md This is a command-line instruction for integrating LiveReload with a Django project. It starts the Django development server with LiveReload capabilities. ```bash python manage.py livereload 127.0.0.1:8000 ``` -------------------------------- ### Configure and Use LiveReload Logger Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/modules.md Demonstrates how to set the logging level for the 'livereload' logger and emit informational and error messages. Ensure the 'logging' module is imported. ```python import logging # Configure logging logging.getLogger('livereload').setLevel(logging.DEBUG) # Get logger in your code logger = logging.getLogger('livereload') logger.info('Message') logger.error('Error') ``` -------------------------------- ### Get Watcher Class Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Returns the appropriate watcher class based on system availability. Use this to instantiate a watcher that suits your environment. ```python def get_watcher_class() ``` ```python from livereload.watcher import get_watcher_class WatcherClass = get_watcher_class() watcher = WatcherClass() # On Linux with pyinotify: INotifyWatcher (event-based) # On other systems or without pyinotify: Watcher (polling) ``` -------------------------------- ### File Watching Options Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Demonstrates various ways to configure file watching, including watching directories, executing commands, setting delays, and custom ignore functions. ```APIDOC ## File Watching ### Description Provides flexible options for monitoring file system changes. ### Examples - **Watch directory:** `server.watch('src/')` - **Watch with command:** `server.watch('*.less', shell('lessc *.less'))` - **Watch with delay:** `server.watch('src/', shell('build'), delay=2.0)` - **Custom ignore function:** `server.watch('.', ignore=lambda f: '.git' in f)` ``` -------------------------------- ### LiveReload Server with Flask Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Integrate LiveReload with a Flask application. This setup enables automatic reloading of templates and browser refreshes on changes. ```python from flask import Flask from livereload import Server app = Flask(__name__) app.config['TEMPLATES_AUTO_RELOAD'] = True server = Server(app.wsgi_app) server.watch('templates/') server.serve(port=5000, open_url_delay=1) ``` -------------------------------- ### Get Content Modified Time Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Retrieves the modification time of a file for cache validation. Uses os.stat() and converts the mtime to a UTC datetime. ```python @classmethod get_content_modified_time(cls, abspath) ``` -------------------------------- ### Basic Flask Integration with LiveReload Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Set up a basic Flask application with the LiveReload server. This snippet shows how to initialize the server with your Flask WSGI app and watch specific directories for changes. ```python from flask import Flask from livereload import Server app = Flask(__name__) # Configure your Flask app @app.route('/') def index(): return 'Hello World' # Create LiveReload server with Flask WSGI app server = Server(app.wsgi_app) # Optional: watch specific directories server.watch('templates/') server.watch('static/') # Start server if __name__ == '__main__': server.serve() ``` -------------------------------- ### server.application() Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md Configures the Tornado web application handlers, used internally by the `serve()` method. ```APIDOC #### application() ```python server.application(port, host, liveport=None, debug=None, live_css=True) ``` Creates and configures the Tornado web application handlers. Called internally by `serve()`. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | port | int | Yes | — | Main server port for serving files or proxying WSGI app. | | host | str | Yes | — | Bind hostname (e.g., '127.0.0.1' or '0.0.0.0'). | | liveport | int or None | No | None | Separate WebSocket port for LiveReload. If None, uses main port. | | debug | bool or None | No | None | Enable Tornado debug mode (auto-reload on code changes). If None, True when app is set, False otherwise. | | live_css | bool | No | True | Enable live CSS reloading (CSS changes reload without full page reload). If False, all changes force full reload. | **Source:** `livereload/server.py:251` ``` -------------------------------- ### Import Server and Shell from livereload Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Import the main Server class and the shell command wrapper function from the livereload package. ```python from livereload import Server, shell ``` -------------------------------- ### LiveReload Server Serve Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/endpoints.md Configure the server port, host, root directory, default filename, and live CSS flag. ```python server.serve( port=5500, liveport=None, host='127.0.0.1', root='.', debug=None, live_css=True, default_filename='index.html' ) ``` -------------------------------- ### Development Server Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Configure the development server with auto-reloading, browser opening delay, and smart CSS reload. Ensure livereload is imported and the application is created. ```python from livereload import Server app = create_app() server = Server(app.wsgi_app) server.watch('templates/') server.watch('static/') server.serve( port=5000, debug=True, # Auto-reload on Python changes open_url_delay=2, # Open browser automatically live_css=True # Smart CSS reload ) ``` -------------------------------- ### Build and Reload Pattern Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/index.md Configure watchers to execute build commands and then watch for changes in the output directory. ```python server.watch('src/', shell('npm run build'), delay='forever') server.watch('dist/') ``` -------------------------------- ### get_watcher_class() Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Returns the appropriate watcher class based on system availability and installed dependencies like pyinotify. It defaults to a polling-based Watcher if event-based notification is not supported. ```APIDOC ## get_watcher_class() ### Description Returns the appropriate watcher class based on system availability. It defaults to a polling-based Watcher if event-based notification is not supported. ### Returns - **type**: The watcher class (e.g., `INotifyWatcher` or `Watcher`). ### Logic - Returns `Watcher` (polling) if: - `pyinotify` is not installed, OR - `pyinotify` doesn't have `TornadoAsyncNotifier` (old version). - Returns `INotifyWatcher` if `pyinotify` is available with `TornadoAsyncNotifier`. ### Example ```python from livereload.watcher import get_watcher_class WatcherClass = get_watcher_class() watcher = WatcherClass() # On Linux with pyinotify: INotifyWatcher (event-based) # On other systems or without pyinotify: Watcher (polling) ``` ``` -------------------------------- ### Initialize INotifyWatcher Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Initializes the watcher with pyinotify's WatchManager and prepares for event handling. Requires the pyinotify package. ```python INotifyWatcher() ``` -------------------------------- ### LiveReload Auto-Watch Directories Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md The Django management command automatically watches directories in the current project directory for changes. It skips hidden directories and those starting with double underscores. ```python for file in os.listdir('.'): if file[0] != '.' and file[:2] != '__' and os.path.isdir(file): server.watch(file) ``` -------------------------------- ### Module Execution as Script Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/cli.md Shows how to run the livereload module directly as a script using `python -m livereload`. This imports and calls the `main` function. ```python from livereload.cli import main main() ``` -------------------------------- ### Get Changed Glob Files (get_changed_glob_files) Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/watcher.md Checks files matching a glob pattern for changes. It uses glob.glob and calls is_file_changed on each match, returning a list of paths that have changed. ```python get_changed_glob_files(path, ignore=None) ``` -------------------------------- ### Manual Reload Trigger (GET /forcereload) Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/endpoints.md Use this endpoint to manually trigger a reload of assets. You can specify a particular file, directory, or pattern to reload, or reload all assets by default. ```http GET /forcereload ``` ```http GET /forcereload?path=* ``` ```http GET /forcereload?path=style.css ``` ```http GET /forcereload?path=static/ ``` -------------------------------- ### Get Cached Version with Mtime Validation Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/handlers.md Retrieves a cached version hash for a file, validating it against the current modification time. Recomputes the hash if the file has changed. This method is thread-safe. ```python @classmethod def _get_cached_version(cls, abs_path) ``` -------------------------------- ### Custom Port and Host with LiveReload CLI Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Configure the host and port for the LiveReload server. Use this to avoid conflicts or make the server accessible on your network. ```bash $ livereload -p 8080 --host 0.0.0.0 ``` -------------------------------- ### Configure Custom Address and Port for LiveReload Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/integrations.md Specify a custom host and port for the Django development server when running the livereload command. Examples include '127.0.0.1:8000', '0.0.0.0:8080', and 'localhost:5000'. ```bash python manage.py livereload 127.0.0.1:8000 ``` ```bash python manage.py livereload 0.0.0.0:8080 ``` ```bash python manage.py livereload localhost:5000 ``` -------------------------------- ### CLI Serve Different Directory and Watch Target Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Serve files from a specified directory (e.g., ./dist) while watching for changes in another directory (e.g., ./src). ```bash # Watch different directory live-reload ./dist --target ./src ``` -------------------------------- ### Get Tornado Web Handlers Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/server.md Returns Tornado handler configuration for web routes, based on whether a WSGI app is set. Used internally for setting up server routes. ```python server.get_web_handlers(script) ``` -------------------------------- ### Watch with delay for build process Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Watch a directory and execute a build command, with a specified delay before the reload occurs. This is useful for build processes that take time to complete. ```python # Watch with delay (for build process) server.watch('src/', shell('npm run build'), delay=2) ``` -------------------------------- ### Server Serve Configuration Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/endpoints.md Parameters for the `server.serve` function, which configures the server for static file serving and live reloading. ```APIDOC ## server.serve() Parameters ### Description Configures the server for static file serving and live reloading. ### Parameters #### General - **port** (int) - Required - Main server port. - **liveport** (int or None) - Optional - Port for livereload specific endpoints. - **host** (str) - Required - Bind address for the server. - **root** (str) - Optional - Root directory for static file serving (default: current directory). - **debug** (bool or None) - Optional - Enable debug mode. - **live_css** (bool) - Optional - Controls liveCSS flag in reload messages (default: True). - **default_filename** (str) - Optional - File served when a directory is requested (default: 'index.html'). ``` -------------------------------- ### Separate WebSocket Port Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/examples.md Configure a livereload server to use a different port for WebSockets than for serving content. This is useful in network setups where the standard LiveReload port might be firewalled or unavailable. ```python from livereload import Server server = Server() server.serve( port=8000, # Content on 8000 liveport=35729, # WebSocket on standard LiveReload port host='0.0.0.0' ) ``` -------------------------------- ### Server Class API Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/MANIFEST.md Documentation for the Server class, including its constructor, public methods, and attributes. ```APIDOC ## Server Class ### Description Provides the core functionality for live reloading. ### Constructor * **`__init__(root='.', default_filename='index.html', watcher=None, app=None, ...)`** - Initializes the server with specified root directory, default filename, watcher, and WSGI application. ### Public Methods * **`watch(path, callback=None, *, delay=0.1, ignore=None)`** - Watches a given path for changes and executes a callback. - **Parameters:** - `path` (str): The path to watch. - `callback` (callable, optional): Function to call on change. - `delay` (float): Delay in seconds before triggering callback. - `ignore` (callable or list, optional): Patterns or function to ignore files. * **`setHeader(name, value)`** - Sets a custom HTTP header for the server. - **Parameters:** - `name` (str): The header name. - `value` (str): The header value. * **`serve(host='127.0.0.1', port=5500, ...)`** - Starts the live reload server. - **Parameters:** - `host` (str): Host to bind to. - `port` (int): Port to listen on. - ... (10 parameters total with defaults and descriptions) * **`application()`** - Returns the WSGI application. ### Attributes * **`root`** (str): The root directory for serving files. * **`app`** (callable): The WSGI application. * **`watcher`** (object): The watcher instance. * **`default_filename`** (str): The default filename to serve. ``` -------------------------------- ### Root Endpoint (Catch-all) Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/endpoints.md The root endpoint '/' handles both GET and HEAD requests. It can either serve static files from a configured root directory or act as a proxy for a WSGI application, injecting LiveReload scripts as needed. ```APIDOC ## GET / (catch-all) ### Description Handles static file serving or WSGI app proxying. Injects LiveReload script into HTML responses. ### Method GET, HEAD ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None provided ### Response #### Success Response (200) Serves static files or proxied WSGI application responses. HTML responses will have the LiveReload script injected. #### Response Example None provided ``` -------------------------------- ### CLI Serve with Custom Port Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/README.md Run the livereload server on a custom port. Replace 8000 with your desired port number. ```bash # Custom port live-reload -p 8000 ``` -------------------------------- ### Serve Specific Directory with LiveReload CLI Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Specify a directory to serve using the LiveReload CLI. Useful when your web assets are not in the root project directory. ```bash $ livereload ./public ``` -------------------------------- ### Basic Static File Server Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/examples.md Serve files from a specified directory with auto-reload enabled on file changes. Access the served content via HTTP. ```python from livereload import Server server = Server() server.serve(root='./public', port=8000) ``` -------------------------------- ### Serve Livereload Server with WSGI App and Debug Mode Source: https://github.com/lepture/python-livereload/blob/master/_autodocs/configuration.md Configures the livereload server to proxy requests for a WSGI application (Flask example) and enables debug mode. Debug mode is automatically detected as True when a WSGI app is provided. ```python from flask import Flask app = Flask(__name__) from livereload import Server server = Server(app.wsgi_app) server.serve( port=5000, debug=True, # Auto-detects True because app is set open_url_delay=2 ) ```