0
# Server Management
1
2
Core server functionality for running LiveReload development servers with HTTP serving, WebSocket communication, and file watching integration.
3
4
## Capabilities
5
6
### Server Initialization
7
8
Create server instances with optional WSGI application integration and custom file watcher configuration.
9
10
```python { .api }
11
class Server:
12
def __init__(self, app=None, watcher=None):
13
"""
14
Initialize LiveReload server.
15
16
Args:
17
app: WSGI application to serve (optional, serves static files if None)
18
watcher: Custom Watcher instance (optional, auto-detects best available)
19
"""
20
```
21
22
**Usage Examples:**
23
24
```python
25
# Basic static file server
26
server = Server()
27
28
# Server with WSGI application (Flask, Django, etc.)
29
from myapp import app
30
server = Server(app)
31
32
# Server with custom watcher
33
from livereload.watcher import get_watcher_class
34
CustomWatcher = get_watcher_class()
35
watcher = CustomWatcher()
36
server = Server(watcher=watcher)
37
```
38
39
### HTTP Serving Configuration
40
41
Start the development server with comprehensive configuration options for ports, hostnames, and development features.
42
43
```python { .api }
44
def serve(self, port=5500, liveport=None, host=None, root=None, debug=None,
45
open_url=False, restart_delay=2, open_url_delay=None,
46
live_css=True, default_filename='index.html'):
47
"""
48
Start serving the server with given configuration.
49
50
Args:
51
port (int): HTTP server port (default: 5500)
52
liveport (int): LiveReload WebSocket port (optional, auto-assigned)
53
host (str): Server hostname (default: '127.0.0.1')
54
root (str): Static file root directory (optional)
55
debug (bool): Enable debug mode with auto-reloading (optional)
56
open_url (bool): Automatically open browser (default: False)
57
restart_delay (int): Delay before restart in seconds (default: 2)
58
open_url_delay (float): Delay before opening browser in seconds (optional)
59
live_css (bool): Enable live CSS reloading (default: True)
60
default_filename (str): Default file to serve (default: 'index.html')
61
"""
62
```
63
64
**Usage Examples:**
65
66
```python
67
# Basic serving
68
server.serve()
69
70
# Custom port and host
71
server.serve(port=8080, host='0.0.0.0')
72
73
# Development mode with auto-open browser
74
server.serve(open_url_delay=2, debug=True)
75
76
# Custom static root with specific default file
77
server.serve(root='/path/to/static', default_filename='home.html')
78
79
# Production-like serving (no debug, no live CSS)
80
server.serve(debug=False, live_css=False)
81
```
82
83
### File Watching Registration
84
85
Register files, directories, or glob patterns for monitoring with optional callback functions and custom delays.
86
87
```python { .api }
88
def watch(self, filepath, func=None, delay=None, ignore=None):
89
"""
90
Add filepath to watcher list.
91
92
Args:
93
filepath (str): File path, directory path, or glob pattern to watch
94
func (callable): Callback function when changes detected (optional)
95
delay (float): Reload delay in seconds (optional)
96
ignore (callable): Function to determine ignored files (optional)
97
"""
98
```
99
100
**Usage Examples:**
101
102
```python
103
# Watch current directory
104
server.watch('.')
105
106
# Watch specific files
107
server.watch('index.html')
108
server.watch('styles/main.css')
109
110
# Watch with glob patterns
111
server.watch('templates/*.html')
112
server.watch('**/*.py')
113
114
# Watch with callback function
115
def rebuild():
116
print("Rebuilding project...")
117
# Custom build logic here
118
119
server.watch('src/', rebuild)
120
121
# Watch with shell command callback
122
server.watch('styles/*.less', shell('lessc styles/main.less styles/main.css'))
123
124
# Watch with custom delay and ignore function
125
def ignore_temp_files(filename):
126
return filename.endswith('.tmp')
127
128
server.watch('project/', delay=1.0, ignore=ignore_temp_files)
129
```
130
131
### HTTP Header Configuration
132
133
Add or override HTTP headers for all server responses.
134
135
```python { .api }
136
def setHeader(self, name, value):
137
"""
138
Add or override HTTP headers at request start.
139
140
Args:
141
name (str): Header field name
142
value (str): Header field value
143
"""
144
```
145
146
**Usage Examples:**
147
148
```python
149
# Add CORS headers
150
server.setHeader('Access-Control-Allow-Origin', '*')
151
server.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
152
153
# Add caching headers
154
server.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
155
156
# Add custom headers
157
server.setHeader('X-Development-Server', 'LiveReload/2.7.1')
158
```
159
160
### Shell Command Integration
161
162
Execute shell commands as file change callbacks with support for build tools, preprocessors, and development workflows.
163
164
```python { .api }
165
def shell(cmd, output=None, mode='w', cwd=None, shell=False):
166
"""
167
Execute a shell command as a file watcher callback.
168
169
Args:
170
cmd (str or list): Shell command to execute
171
output (str): Output file path (optional, defaults to devnull)
172
mode (str): File write mode for output (default: 'w')
173
cwd (str): Working directory for command execution (optional)
174
shell (bool): Use shell for command execution (default: False)
175
176
Returns:
177
callable: Function that can be used as a watcher callback
178
"""
179
```
180
181
**Usage Examples:**
182
183
```python
184
# Compile LESS to CSS
185
server.watch('styles/*.less', shell('lessc styles/main.less styles/main.css'))
186
187
# Compile TypeScript
188
server.watch('src/*.ts', shell('tsc', output='dist/bundle.js'))
189
190
# Run tests on Python file changes
191
server.watch('tests/*.py', shell(['python', '-m', 'pytest', 'tests/']))
192
193
# Custom build script with working directory
194
server.watch('package.json', shell('./build.sh', cwd='/path/to/project'))
195
196
# Complex command with shell features
197
server.watch('docs/*.md', shell('pandoc docs/*.md -o dist/docs.html', shell=True))
198
```
199
200
### WSGI Application Integration
201
202
Integration with WSGI applications for full-stack development with live reloading.
203
204
**Usage Examples:**
205
206
```python
207
# Flask integration
208
from flask import Flask
209
app = Flask(__name__)
210
211
@app.route('/')
212
def hello():
213
return 'Hello World!'
214
215
server = Server(app)
216
server.watch('templates/')
217
server.watch('static/')
218
server.serve()
219
220
# Django integration (alternative to management command)
221
import os
222
from django.core.wsgi import get_wsgi_application
223
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
224
app = get_wsgi_application()
225
226
server = Server(app)
227
server.watch('myapp/templates/')
228
server.watch('myapp/static/')
229
server.serve(port=8000)
230
```
231
232
## Advanced Usage
233
234
### Custom Development Workflows
235
236
```python
237
# Multi-step build process
238
def build_assets():
239
# Compile SASS
240
subprocess.run(['sass', 'scss/main.scss', 'static/css/main.css'])
241
# Optimize images
242
subprocess.run(['imagemin', 'images/*', '--out-dir=static/images/'])
243
# Bundle JavaScript
244
subprocess.run(['webpack', '--mode=development'])
245
246
server = Server()
247
server.watch('scss/', build_assets)
248
server.watch('images/', build_assets)
249
server.watch('js/', build_assets)
250
server.serve(port=3000, open_url_delay=1)
251
```
252
253
### Production-Ready Development Server
254
255
```python
256
server = Server()
257
server.setHeader('X-Frame-Options', 'DENY')
258
server.setHeader('X-Content-Type-Options', 'nosniff')
259
server.setHeader('X-XSS-Protection', '1; mode=block')
260
261
# Watch only specific file types
262
server.watch('**/*.html')
263
server.watch('**/*.css')
264
server.watch('**/*.js')
265
266
server.serve(
267
host='0.0.0.0', # Allow external connections
268
port=8080,
269
debug=False, # Disable debug mode
270
live_css=True, # Keep CSS live reloading
271
restart_delay=1 # Faster restarts
272
)
273
```
274
275
### Handler Classes (Advanced)
276
277
Internal handler classes for advanced customization and integration with Tornado web framework.
278
279
```python { .api }
280
class LiveReloadHandler(WebSocketHandler):
281
"""
282
WebSocket handler for browser-server communication.
283
284
Manages client connections and broadcasts reload notifications.
285
"""
286
287
def check_origin(self, origin):
288
"""Allow cross-origin WebSocket connections."""
289
return True
290
291
def on_close(self):
292
"""Handle client disconnection."""
293
pass
294
295
def send_message(self, message):
296
"""Send message to connected client."""
297
pass
298
299
class StaticFileHandler(MtimeStaticFileHandler):
300
"""
301
Enhanced static file handler with modification time support.
302
303
Extends Tornado's StaticFileHandler with custom headers and caching.
304
"""
305
306
def set_default_headers(self):
307
"""Set default HTTP headers for all responses."""
308
pass
309
310
class LiveReloadJSHandler(RequestHandler):
311
"""Handler serving the LiveReload JavaScript client."""
312
313
def get(self):
314
"""Serve livereload.js client script."""
315
pass
316
317
class ForceReloadHandler(RequestHandler):
318
"""Handler for triggering manual page reloads."""
319
320
def post(self):
321
"""Force reload all connected clients."""
322
pass
323
```
324
325
**Advanced Handler Usage:**
326
327
```python
328
from livereload.handlers import LiveReloadHandler, StaticFileHandler
329
from tornado import web
330
331
# Custom application with LiveReload handlers
332
app = web.Application([
333
(r'/livereload', LiveReloadHandler),
334
(r'/static/(.*)', StaticFileHandler, {'path': './static'}),
335
])
336
337
# Custom handler setup
338
LiveReloadHandler.watcher = watcher
339
LiveReloadHandler.live_css = True
340
```