0
# Server Management
1
2
Primary functions for creating and managing WSGI servers, providing both high-level convenience functions and lower-level server instances for advanced control.
3
4
## Capabilities
5
6
### High-Level Server Function
7
8
The primary entry point for serving WSGI applications with automatic server configuration and startup.
9
10
```python { .api }
11
def serve(app, **kw):
12
"""
13
Serve a WSGI application using waitress server.
14
15
Parameters:
16
- app: WSGI application callable
17
- **kw: Configuration parameters (see Adjustments class)
18
19
Common Parameters:
20
- host (str): Hostname to bind to (default: '0.0.0.0')
21
- port (int): Port to bind to (default: 8080)
22
- threads (int): Number of worker threads (default: 4)
23
- unix_socket (str): Unix socket path (Unix only)
24
- connection_limit (int): Max concurrent connections (default: 100)
25
- channel_timeout (int): Idle connection timeout (default: 120)
26
27
Returns:
28
None (blocks until server shutdown)
29
"""
30
```
31
32
Usage example:
33
34
```python
35
from waitress import serve
36
37
def my_app(environ, start_response):
38
status = '200 OK'
39
headers = [('Content-type', 'text/html')]
40
start_response(status, headers)
41
return [b'<h1>Hello World!</h1>']
42
43
# Basic usage
44
serve(my_app)
45
46
# With configuration
47
serve(my_app, host='127.0.0.1', port=5000, threads=6)
48
49
# Unix socket (Linux/macOS)
50
serve(my_app, unix_socket='/tmp/waitress.sock')
51
```
52
53
### Low-Level Server Creation
54
55
Creates server instances for advanced control over server lifecycle and configuration.
56
57
```python { .api }
58
def create_server(application, map=None, _start=True, _sock=None, _dispatcher=None, **kw):
59
"""
60
Create a WSGI server instance.
61
62
Parameters:
63
- application: WSGI application callable
64
- map (dict): asyncore socket map (default: None, creates new map)
65
- _start (bool): Whether to start listening immediately (default: True)
66
- _sock: Pre-existing socket to use (default: None)
67
- _dispatcher: Custom task dispatcher (default: None, creates ThreadedTaskDispatcher)
68
- **kw: Configuration parameters (see Adjustments class)
69
70
Returns:
71
Server instance (TcpWSGIServer, UnixWSGIServer, or MultiSocketServer)
72
"""
73
```
74
75
Usage example:
76
77
```python
78
from waitress import create_server
79
80
def my_app(environ, start_response):
81
# Your WSGI app here
82
pass
83
84
# Create server without starting
85
server = create_server(my_app, _start=False, host='localhost', port=8080)
86
87
# Custom startup logic
88
print(f"Starting server on {server.effective_host}:{server.effective_port}")
89
server.run() # Start the server loop
90
91
# Multiple servers
92
servers = []
93
for port in [8080, 8081, 8082]:
94
server = create_server(my_app, port=port)
95
servers.append(server)
96
```
97
98
### Paste Integration
99
100
Entry point for Paste deployment configurations.
101
102
```python { .api }
103
def serve_paste(app, global_conf, **kw):
104
"""
105
Paste deployment entry point.
106
107
Parameters:
108
- app: WSGI application
109
- global_conf: Paste global configuration
110
- **kw: Waitress configuration parameters
111
112
Returns:
113
int: Exit code (always 0)
114
"""
115
```
116
117
Used in Paste deployment files:
118
119
```ini
120
[server:main]
121
use = egg:waitress#main
122
host = 0.0.0.0
123
port = 6543
124
```
125
126
### Server Classes
127
128
The server classes returned by `create_server()` provide direct control over server lifecycle.
129
130
```python { .api }
131
class BaseWSGIServer:
132
"""Base class for all WSGI server implementations."""
133
134
def run(self):
135
"""Start the asyncore event loop (blocking)."""
136
137
def close(self):
138
"""Shutdown the server cleanly."""
139
140
def print_listen(self, format_str):
141
"""Print server listening information."""
142
143
class TcpWSGIServer(BaseWSGIServer):
144
"""TCP/IP socket-based WSGI server."""
145
146
effective_host: str # Actual bound hostname
147
effective_port: int # Actual bound port
148
149
class UnixWSGIServer(BaseWSGIServer):
150
"""Unix domain socket WSGI server (Unix platforms only)."""
151
152
effective_host: str # Socket path
153
154
class MultiSocketServer:
155
"""Manages multiple socket servers simultaneously."""
156
157
def run(self):
158
"""Start all managed servers."""
159
160
def close(self):
161
"""Shutdown all managed servers."""
162
```
163
164
Usage example:
165
166
```python
167
from waitress import create_server
168
169
server = create_server(my_app, host='0.0.0.0', port=8080)
170
171
try:
172
print(f"Server running on {server.effective_host}:{server.effective_port}")
173
server.run()
174
except KeyboardInterrupt:
175
print("Shutting down...")
176
server.close()
177
```
178
179
### Performance Profiling
180
181
Utility function for profiling server performance and application code.
182
183
```python { .api }
184
def profile(cmd, globals, locals, sort_order=None, callers=False):
185
"""
186
Run a command under the Python profiler and print results.
187
188
Parameters:
189
- cmd (str): Command string to execute and profile
190
- globals (dict): Global namespace for command execution
191
- locals (dict): Local namespace for command execution
192
- sort_order (tuple): Sort order for profile stats (default: ('cumulative', 'calls', 'time'))
193
- callers (bool): Print caller information instead of stats (default: False)
194
195
Returns:
196
None (prints profiling output to stdout)
197
198
Usage:
199
Used internally by serve() when _profile=True parameter is passed.
200
"""
201
```
202
203
Usage example:
204
205
```python
206
import waitress
207
208
def my_app(environ, start_response):
209
# Your WSGI application
210
status = '200 OK'
211
headers = [('Content-type', 'text/plain')]
212
start_response(status, headers)
213
return [b'Hello World']
214
215
# Profile the server startup and initial request handling
216
waitress.profile(
217
"waitress.serve(my_app, port=8080)",
218
globals(),
219
locals(),
220
sort_order=('cumulative', 'time'),
221
callers=False
222
)
223
```