Werkzeug Documentation
repository·main·Indexed 27 days ago
https://github.com/pallets/werkzeugA comprehensive WSGI web application utility library providing essential tools for web development, including request and response handling, routing, HTTP utilities, and a development server. It features an interactive debugger, a test client, and specialized data structures like MultiDict and FileStorage. Werkzeug serves as the foundation for the Flask web framework and is designed to be unopinionated.
What's inside Werkzeug
- Werkzeug is a comprehensive WSGI web application library designed as a collection of utilities for WSGI applications. It is highly flexible and does not enforce specific dependencies, allowing developers to choose their own template engines, database adapters, and request handling strategies.
Overview of Werkzeug features
mainWerkzeug is a comprehensive WSGI web application utility library. It provides the following core capabilities:
- Interactive Debugger: Inspect stack traces and source code in the browser with an interactive interpreter for any frame.
- Request Handling: A full-featured
Requestobject to interact with headers, query arguments, form data, files, and cookies. - Response Handling: A
Responseobject that can wrap other WSGI applications and handle streaming data. - Routing System: Matches URLs to endpoints and generates URLs, with an extensible system for capturing URL variables.
- HTTP Utilities: Tools for handling entity tags, cache control, dates, user agents, cookies, and files.
- Development Server: A threaded WSGI server for local development.
- Test Client: Simulates HTTP requests during testing without needing a running server.
Werkzeug is unopinionated and does not enforce dependencies like template engines or database adapters. It is the foundation upon which the Flask web framework is built.
Understand the Werkzeug View Function pattern
mainIn Werkzeug documentation, a view function refers to a function that processes an incoming request and returns a response. It is typically called with arequestobject and, depending on your routing setup, optional parameters extracted from a URL rule.Choose a WSGI Server for Production
mainWerkzeug is a WSGI application. To run it in production, you need a WSGI server to convert HTTP requests into the WSGI
environand WSGI responses back into HTTP. Common self-hosted WSGI server options include:gunicornwaitressmod_wsgiuwsgigeventeventlet
Understand the Werkzeug Response Object concept
mainA response object in the context of Werkzeug is any object that behaves like a WSGI application but does not perform request processing. While often implemented using thewerkzeug.wrappers.Responseclass, it is a functional definition: it is the object returned by a view function to be sent back to the server.Understand WSGI middleware in Werkzeug
mainA WSGI middleware is a WSGI application that wraps another application to observe or change its behavior. Werkzeug provides several built-in middleware components for common use cases, including:
proxy_fix: For handling proxy headers.shared_data: For serving static files.dispatcher: For routing requests to different applications.http_proxy: For proxying HTTP requests.lint: For linting WSGI applications.profiler: For profiling WSGI applications.interactive debugger: For debugging (typically used automatically with the Werkzeug development server, but can be applied manually).
Understand WSGI compliance in Werkzeug
mainWerkzeug follows the WSGI (Web Server Gateway Interface) specification (PEP 3333). This ensures that Werkzeug applications, servers, and utilities are interoperable and can work together seamlessly.Use General Purpose Data Structures in Werkzeug
mainWerkzeug provides specialized subclasses of common Python objects to extend functionality, such as immutability or specific semantics.
Key general-purpose classes include:
MultiDict: A dictionary that can hold multiple values for a single key.CombinedMultiDict: A dictionary that combines multipleMultiDictinstances.ImmutableDict: An immutable version of a dictionary.ImmutableList: An immutable version of a list.FileMultiDict: AMultiDictspecifically designed to handle file uploads.TypeConversionDict: A dictionary that handles type conversion.ImmutableTypeConversionDict: An immutable version ofTypeConversionDict.
Note:
FileMultiDictis not pickleable if it contains a file.Use WSGI Helpers in werkzeug.wsgi
mainThewerkzeug.wsgimodule provides classes and functions to simplify working with the WSGI specification or operating directly on the WSGI layer. While these helpers are available for low-level manipulation, most of this functionality is also exposed through Werkzeug's high-level wrappers.Use HTTP Related Data Structures in Werkzeug
mainWerkzeug provides several data structures specifically designed to work with HTTP semantics, such as headers and content negotiation:
Headers and Environments:
Headers([defaults]): Represents HTTP headers.EnvironHeaders: Headers derived from a WSGI environment.HeaderSet: A collection of headers.
Content Negotiation:
Accept: Handles theAcceptheader.MIMEAccept: Specialized for MIME types (includesaccept_html,accept_xhtml,accept_json).CharsetAccept: Handles character set negotiation.LanguageAccept: Handles language negotiation.
Cache and Authentication:
RequestCacheControl/ResponseCacheControl: Manage cache control directives.ETags: Manage entity tags.Authorization: Manage authentication credentials.WWWAuthenticate: Manage authentication challenges.IfRange: Manage conditional requests.Range/ContentRange: Manage byte range requests.
Quickstart URL Routing with Map and Rule
mainTo implement URL routing, import
MapandRulefromwerkzeug.routing. Create aMapcontaining a list ofRuleobjects. EachRuledefines a URL path and anendpoint(an alias for the view function). Inside your WSGI application, useurl_map.bind_to_environ(environ)to create aMapAdapter, then call.match()to retrieve the(endpoint, args)tuple or handle exceptions likeNotFound,MethodNotAllowed, orRequestRedirect.from werkzeug.routing import Map, Rule, NotFound, RequestRedirect url_map = Map([ Rule('/', endpoint='blog/index'), Rule('/<int:year>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/<int:day>/<slug>', endpoint='blog/show_post'), Rule('/about', endpoint='blog/about_me'), Rule('/feeds/', endpoint='blog/feeds'), Rule('/feeds/<feed_name>.rss', endpoint='blog/show_feed') ]) def application(environ, start_response): urls = url_map.bind_to_environ(environ) try: endpoint, args = urls.match() except HTTPException as e: return e(environ, start_response) start_response('200 OK', [('Content-Type', 'text/plain')]) return [f'Rule points to {endpoint!r} with arguments {args!r}'.encode()]Configure gevent network binding and security
mainWhen deploying
gevent, follow these security and networking best practices:- Avoid running as root: Do not run
geventas root to prevent application code from running with elevated privileges. - Use a reverse proxy: Since
geventshould not run as root, it cannot bind to privileged ports like 80 or 443. Use a reverse proxy likenginxorapache-httpdin front of thegeventserver. - Binding to all interfaces: To bind to all external IPs on a non-privileged port, use
0.0.0.0in the server address tuple. - Security Warning: If using a reverse proxy, do not bind to
0.0.0.0, as this allows users to bypass the proxy and connect directly to the server. Use a specific IP address instead.
- Avoid running as root: Do not run