The comprehensive WSGI web application library providing essential utilities and components for building Python web applications.
npx @tessl/cli install tessl/pypi-werkzeug@3.1.0The 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.
pip install Werkzeugimport werkzeugMost common imports for web development:
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from werkzeug.test import ClientCommon imports for specific functionality:
# URL routing
from werkzeug.routing import Map, Rule
# HTTP utilities
from werkzeug.http import parse_date, http_date
# Data structures
from werkzeug.datastructures import MultiDict, Headers
# Security utilities
from werkzeug.security import generate_password_hash, check_password_hash
# Middleware
from werkzeug.middleware.shared_data import SharedDataMiddlewarefrom werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
def application(environ, start_response):
"""Simple WSGI application."""
request = Request(environ)
if request.path == '/':
response = Response('Hello World!')
elif request.path == '/json':
response = Response(
'{"message": "Hello JSON"}',
mimetype='application/json'
)
else:
response = Response('Not Found', status=404)
return response(environ, start_response)
# Run development server
if __name__ == '__main__':
run_simple('localhost', 8000, application, use_debugger=True, use_reloader=True)Testing the application:
from werkzeug.test import Client
client = Client(application)
response = client.get('/')
print(response.data.decode()) # "Hello World!"Werkzeug follows a modular architecture organized around core WSGI concepts:
This design provides the foundational WSGI functionality while maintaining flexibility for higher-level frameworks to add structure and patterns.
Complete WSGI request and response wrappers with full HTTP feature support including headers, cookies, form data, file uploads, content negotiation, and conditional requests.
class Request:
def __init__(self, environ, populate_request=True, shallow=False): ...
# Properties for accessing request data
method: str
url: str
path: str
args: MultiDict
form: MultiDict
files: MultiDict
json: Any
headers: Headers
cookies: dict
def get_json(self, force=False, silent=False, cache=True): ...
class Response:
def __init__(self, response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False): ...
# Properties for response configuration
data: bytes
status_code: int
headers: Headers
mimetype: str
def set_cookie(self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None): ...
def make_conditional(self, request_or_environ, accept_ranges=False, complete_length=None): ...Flexible URL routing system for mapping URLs to endpoints with support for URL variables, converters, HTTP methods, and URL generation.
class Map:
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): ...
def add(self, rule_factory): ...
def bind(self, server_name, script_name="/", subdomain=None, url_scheme="http", path_info=None, method="GET", query_args=None): ...
class Rule:
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): ...
class MapAdapter:
def match(self, path_info=None, method=None, return_rule=False, query_args=None): ...
def build(self, endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None): ...Specialized data structures for handling HTTP-specific data including multi-value dictionaries, headers, file uploads, and accept headers with proper parsing and type conversion.
class MultiDict:
def __init__(self, mapping=None): ...
def get(self, key, default=None, type=None): ...
def getlist(self, key, type=None): ...
def add(self, key, value): ...
class Headers:
def __init__(self, defaults=None): ...
def get(self, key, default=None, type=None): ...
def set(self, _key, _value, **kw): ...
def add(self, _key, _value, **kw): ...
class FileStorage:
filename: Optional[str]
content_type: Optional[str]
headers: Headers
def save(self, dst, buffer_size=16384): ...Comprehensive HTTP parsing and formatting utilities for headers, cookies, dates, ETags, cache control, content negotiation, and form data parsing.
def parse_date(value): ...
def http_date(timestamp=None): ...
def parse_cookie(header, cls=None): ...
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): ...
def generate_etag(data): ...
def parse_accept_header(value, cls=None): ...
def parse_cache_control_header(value, on_update=None, cls=None): ...
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): ...Complete test client and utilities for testing WSGI applications including request simulation, cookie handling, redirect following, and response validation.
class Client:
def __init__(self, application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False): ...
def open(self, *args, **kwargs): ...
def get(self, *args, **kwargs): ...
def post(self, *args, **kwargs): ...
def put(self, *args, **kwargs): ...
def delete(self, *args, **kwargs): ...
class EnvironBuilder:
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): ...
def get_environ(self): ...Feature-rich WSGI development server with automatic reloading, interactive debugging, SSL support, and multi-threading capabilities.
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): ...
def make_server(host, port, app, threaded=False, processes=1, request_handler=None, passthrough_errors=False, ssl_context=None, fd=None): ...
class DebuggedApplication:
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): ...Collection of WSGI middleware components for common functionality including static file serving, proxy handling, profiling, and application dispatching.
class SharedDataMiddleware:
def __init__(self, app, exports, disallow=None, cache=True, cache_timeout=43200, fallback_mimetype="text/plain"): ...
class ProxyFix:
def __init__(self, app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0): ...
class DispatcherMiddleware:
def __init__(self, app, mounts=None): ...Security functions for password hashing, secure filename handling, and safe filesystem operations.
def generate_password_hash(password, method="pbkdf2:sha256", salt_length=16): ...
def check_password_hash(pwhash, password): ...
def secure_filename(filename): ...
def safe_join(directory, *pathnames): ...URL processing functions and WSGI utilities for encoding, decoding, parsing, and manipulating URLs and WSGI environments.
def url_encode(obj, charset="utf-8", encode_keys=False, sort=False, key=None, separator="&"): ...
def url_decode(s, charset="utf-8", decode_keys=False, separator="&", cls=None, errors="replace"): ...
def url_quote(string, charset="utf-8", errors="strict", safe="/:"): ...
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None): ...
def get_host(environ, trusted_hosts=None): ...Complete HTTP exception hierarchy for proper error handling and response codes with WSGI integration.
class HTTPException(Exception):
code: int
description: str
def get_response(self, environ=None, scope=None): ...
class BadRequest(HTTPException): ... # 400
class Unauthorized(HTTPException): ... # 401
class Forbidden(HTTPException): ... # 403
class NotFound(HTTPException): ... # 404
class MethodNotAllowed(HTTPException): ... # 405
class InternalServerError(HTTPException): ... # 500
def abort(code, *args, **kwargs): ...from typing import Union, Optional, Dict, List, Any, Callable, Tuple, IO
from werkzeug.datastructures import MultiDict, Headers, FileStorage
# Common type aliases used throughout Werkzeug
WSGIEnvironment = Dict[str, Any]
WSGIApplication = Callable[[WSGIEnvironment, Callable], List[bytes]]
StartResponse = Callable[[str, List[Tuple[str, str]]], None]