0
# Werkzeug
1
2
The comprehensive WSGI web application library providing essential utilities and components for building Python web applications. Werkzeug offers a robust toolkit including HTTP request/response handling, URL routing, debugging tools, middleware, testing utilities, and a development server, serving as the foundation for Flask and other Python web frameworks.
3
4
## Package Information
5
6
- **Package Name**: Werkzeug
7
- **Language**: Python
8
- **Installation**: `pip install Werkzeug`
9
- **Version**: 3.1.3
10
11
## Core Imports
12
13
```python
14
import werkzeug
15
```
16
17
Most common imports for web development:
18
19
```python
20
from werkzeug.wrappers import Request, Response
21
from werkzeug.serving import run_simple
22
from werkzeug.test import Client
23
```
24
25
Common imports for specific functionality:
26
27
```python
28
# URL routing
29
from werkzeug.routing import Map, Rule
30
31
# HTTP utilities
32
from werkzeug.http import parse_date, http_date
33
34
# Data structures
35
from werkzeug.datastructures import MultiDict, Headers
36
37
# Security utilities
38
from werkzeug.security import generate_password_hash, check_password_hash
39
40
# Middleware
41
from werkzeug.middleware.shared_data import SharedDataMiddleware
42
```
43
44
## Basic Usage
45
46
```python
47
from werkzeug.wrappers import Request, Response
48
from werkzeug.serving import run_simple
49
50
def application(environ, start_response):
51
"""Simple WSGI application."""
52
request = Request(environ)
53
54
if request.path == '/':
55
response = Response('Hello World!')
56
elif request.path == '/json':
57
response = Response(
58
'{"message": "Hello JSON"}',
59
mimetype='application/json'
60
)
61
else:
62
response = Response('Not Found', status=404)
63
64
return response(environ, start_response)
65
66
# Run development server
67
if __name__ == '__main__':
68
run_simple('localhost', 8000, application, use_debugger=True, use_reloader=True)
69
```
70
71
Testing the application:
72
73
```python
74
from werkzeug.test import Client
75
76
client = Client(application)
77
response = client.get('/')
78
print(response.data.decode()) # "Hello World!"
79
```
80
81
## Architecture
82
83
Werkzeug follows a modular architecture organized around core WSGI concepts:
84
85
- **Request/Response Wrappers**: High-level objects wrapping WSGI environ and response data
86
- **URL Routing**: Flexible system for mapping URLs to endpoints with converters
87
- **Data Structures**: HTTP-aware collections for headers, form data, and multi-value parameters
88
- **Middleware**: Reusable WSGI middleware components for common functionality
89
- **Testing**: Complete test client and utilities for WSGI application testing
90
- **Development Server**: Feature-rich development server with automatic reloading and debugging
91
- **HTTP Utilities**: Low-level HTTP parsing, formatting, and validation functions
92
93
This design provides the foundational WSGI functionality while maintaining flexibility for higher-level frameworks to add structure and patterns.
94
95
## Capabilities
96
97
### Request and Response Handling
98
99
Complete WSGI request and response wrappers with full HTTP feature support including headers, cookies, form data, file uploads, content negotiation, and conditional requests.
100
101
```python { .api }
102
class Request:
103
def __init__(self, environ, populate_request=True, shallow=False): ...
104
105
# Properties for accessing request data
106
method: str
107
url: str
108
path: str
109
args: MultiDict
110
form: MultiDict
111
files: MultiDict
112
json: Any
113
headers: Headers
114
cookies: dict
115
116
def get_json(self, force=False, silent=False, cache=True): ...
117
118
class Response:
119
def __init__(self, response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False): ...
120
121
# Properties for response configuration
122
data: bytes
123
status_code: int
124
headers: Headers
125
mimetype: str
126
127
def set_cookie(self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None): ...
128
def make_conditional(self, request_or_environ, accept_ranges=False, complete_length=None): ...
129
```
130
131
[Request and Response Handling](./request-response.md)
132
133
### URL Routing
134
135
Flexible URL routing system for mapping URLs to endpoints with support for URL variables, converters, HTTP methods, and URL generation.
136
137
```python { .api }
138
class Map:
139
def __init__(self, rules=None, default_subdomain="", charset="utf-8", strict_slashes=True, merge_slashes=True, redirect_defaults=True, converters=None, sort_parameters=True, sort_key=None, host_matching=False): ...
140
def add(self, rule_factory): ...
141
def bind(self, server_name, script_name="/", subdomain=None, url_scheme="http", path_info=None, method="GET", query_args=None): ...
142
143
class Rule:
144
def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, merge_slashes=None, redirect_to=None, alias=False, host=None): ...
145
146
class MapAdapter:
147
def match(self, path_info=None, method=None, return_rule=False, query_args=None): ...
148
def build(self, endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None): ...
149
```
150
151
[URL Routing](./routing.md)
152
153
### HTTP Data Structures
154
155
Specialized data structures for handling HTTP-specific data including multi-value dictionaries, headers, file uploads, and accept headers with proper parsing and type conversion.
156
157
```python { .api }
158
class MultiDict:
159
def __init__(self, mapping=None): ...
160
def get(self, key, default=None, type=None): ...
161
def getlist(self, key, type=None): ...
162
def add(self, key, value): ...
163
164
class Headers:
165
def __init__(self, defaults=None): ...
166
def get(self, key, default=None, type=None): ...
167
def set(self, _key, _value, **kw): ...
168
def add(self, _key, _value, **kw): ...
169
170
class FileStorage:
171
filename: Optional[str]
172
content_type: Optional[str]
173
headers: Headers
174
def save(self, dst, buffer_size=16384): ...
175
```
176
177
[HTTP Data Structures](./data-structures.md)
178
179
### HTTP Utilities
180
181
Comprehensive HTTP parsing and formatting utilities for headers, cookies, dates, ETags, cache control, content negotiation, and form data parsing.
182
183
```python { .api }
184
def parse_date(value): ...
185
def http_date(timestamp=None): ...
186
def parse_cookie(header, cls=None): ...
187
def dump_cookie(key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, charset="utf-8", sync_expires=True, max_size=4093, samesite=None): ...
188
def generate_etag(data): ...
189
def parse_accept_header(value, cls=None): ...
190
def parse_cache_control_header(value, on_update=None, cls=None): ...
191
def parse_form_data(environ, stream_factory=None, max_form_memory_size=None, max_content_length=None, cls=None, silent=True, *, max_form_parts=None): ...
192
```
193
194
[HTTP Utilities](./http-utilities.md)
195
196
### Testing Utilities
197
198
Complete test client and utilities for testing WSGI applications including request simulation, cookie handling, redirect following, and response validation.
199
200
```python { .api }
201
class Client:
202
def __init__(self, application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False): ...
203
def open(self, *args, **kwargs): ...
204
def get(self, *args, **kwargs): ...
205
def post(self, *args, **kwargs): ...
206
def put(self, *args, **kwargs): ...
207
def delete(self, *args, **kwargs): ...
208
209
class EnvironBuilder:
210
def __init__(self, path="/", base_url=None, query_string=None, method="GET", input_stream=None, content_type=None, content_length=None, errors_stream=None, multithread=False, multiprocess=True, run_once=False, headers=None, data=None, environ_base=None, environ_overrides=None, mimetype=None, json=None, auth=None): ...
211
def get_environ(self): ...
212
```
213
214
[Testing Utilities](./testing.md)
215
216
### Development Server
217
218
Feature-rich WSGI development server with automatic reloading, interactive debugging, SSL support, and multi-threading capabilities.
219
220
```python { .api }
221
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, exclude_patterns=None, reloader_interval=1, reloader_type="auto", threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): ...
222
223
def make_server(host, port, app, threaded=False, processes=1, request_handler=None, passthrough_errors=False, ssl_context=None, fd=None): ...
224
225
class DebuggedApplication:
226
def __init__(self, app, evalex=False, request_key="werkzeug.request", console_path="/console", console_init_func=None, show_hidden_frames=True, pin_security=True, pin_logging=True): ...
227
```
228
229
[Development Server](./dev-server.md)
230
231
### Middleware
232
233
Collection of WSGI middleware components for common functionality including static file serving, proxy handling, profiling, and application dispatching.
234
235
```python { .api }
236
class SharedDataMiddleware:
237
def __init__(self, app, exports, disallow=None, cache=True, cache_timeout=43200, fallback_mimetype="text/plain"): ...
238
239
class ProxyFix:
240
def __init__(self, app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0): ...
241
242
class DispatcherMiddleware:
243
def __init__(self, app, mounts=None): ...
244
```
245
246
[Middleware](./middleware.md)
247
248
### Security Utilities
249
250
Security functions for password hashing, secure filename handling, and safe filesystem operations.
251
252
```python { .api }
253
def generate_password_hash(password, method="pbkdf2:sha256", salt_length=16): ...
254
def check_password_hash(pwhash, password): ...
255
def secure_filename(filename): ...
256
def safe_join(directory, *pathnames): ...
257
```
258
259
[Security Utilities](./security.md)
260
261
### URL and WSGI Utilities
262
263
URL processing functions and WSGI utilities for encoding, decoding, parsing, and manipulating URLs and WSGI environments.
264
265
```python { .api }
266
def url_encode(obj, charset="utf-8", encode_keys=False, sort=False, key=None, separator="&"): ...
267
def url_decode(s, charset="utf-8", decode_keys=False, separator="&", cls=None, errors="replace"): ...
268
def url_quote(string, charset="utf-8", errors="strict", safe="/:"): ...
269
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None): ...
270
def get_host(environ, trusted_hosts=None): ...
271
```
272
273
[URL and WSGI Utilities](./url-wsgi-utils.md)
274
275
### Exception Handling
276
277
Complete HTTP exception hierarchy for proper error handling and response codes with WSGI integration.
278
279
```python { .api }
280
class HTTPException(Exception):
281
code: int
282
description: str
283
def get_response(self, environ=None, scope=None): ...
284
285
class BadRequest(HTTPException): ... # 400
286
class Unauthorized(HTTPException): ... # 401
287
class Forbidden(HTTPException): ... # 403
288
class NotFound(HTTPException): ... # 404
289
class MethodNotAllowed(HTTPException): ... # 405
290
class InternalServerError(HTTPException): ... # 500
291
292
def abort(code, *args, **kwargs): ...
293
```
294
295
[Exception Handling](./exceptions.md)
296
297
## Types
298
299
```python { .api }
300
from typing import Union, Optional, Dict, List, Any, Callable, Tuple, IO
301
from werkzeug.datastructures import MultiDict, Headers, FileStorage
302
303
# Common type aliases used throughout Werkzeug
304
WSGIEnvironment = Dict[str, Any]
305
WSGIApplication = Callable[[WSGIEnvironment, Callable], List[bytes]]
306
StartResponse = Callable[[str, List[Tuple[str, str]]], None]
307
```