Werkzeug Documentation

repository·main·Indexed 27 days ago

https://github.com/pallets/werkzeug

A 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.

Tokens
21.2K
Snippets
58
Records
140
Agent score
92%

What's inside Werkzeug

  1. Overview of Werkzeug

    main
    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.
  2. Overview of Werkzeug features

    main

    Werkzeug 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 Request object to interact with headers, query arguments, form data, files, and cookies.
    • Response Handling: A Response object 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.

  3. Understand the Werkzeug View Function pattern

    main
    In Werkzeug documentation, a view function refers to a function that processes an incoming request and returns a response. It is typically called with a request object and, depending on your routing setup, optional parameters extracted from a URL rule.
  4. Choose a WSGI Server for Production

    main

    Werkzeug is a WSGI application. To run it in production, you need a WSGI server to convert HTTP requests into the WSGI environ and WSGI responses back into HTTP. Common self-hosted WSGI server options include:

    • gunicorn
    • waitress
    • mod_wsgi
    • uwsgi
    • gevent
    • eventlet
  5. Understand the Werkzeug Response Object concept

    main
    A 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 the werkzeug.wrappers.Response class, it is a functional definition: it is the object returned by a view function to be sent back to the server.
  6. Understand WSGI middleware in Werkzeug

    main

    A 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).
  7. Understand WSGI compliance in Werkzeug

    main
    Werkzeug 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.
  8. Use General Purpose Data Structures in Werkzeug

    main

    Werkzeug 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 multiple MultiDict instances.
    • ImmutableDict: An immutable version of a dictionary.
    • ImmutableList: An immutable version of a list.
    • FileMultiDict: A MultiDict specifically designed to handle file uploads.
    • TypeConversionDict: A dictionary that handles type conversion.
    • ImmutableTypeConversionDict: An immutable version of TypeConversionDict.

    Note: FileMultiDict is not pickleable if it contains a file.

  9. Use WSGI Helpers in werkzeug.wsgi

    main
    The werkzeug.wsgi module 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.
  10. Use HTTP Related Data Structures in Werkzeug

    main

    Werkzeug 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 the Accept header.
    • MIMEAccept: Specialized for MIME types (includes accept_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.
  11. Quickstart URL Routing with Map and Rule

    main

    To implement URL routing, import Map and Rule from werkzeug.routing. Create a Map containing a list of Rule objects. Each Rule defines a URL path and an endpoint (an alias for the view function). Inside your WSGI application, use url_map.bind_to_environ(environ) to create a MapAdapter, then call .match() to retrieve the (endpoint, args) tuple or handle exceptions like NotFound, MethodNotAllowed, or RequestRedirect.

    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()]
  12. Configure gevent network binding and security

    main

    When deploying gevent, follow these security and networking best practices:

    • Avoid running as root: Do not run gevent as root to prevent application code from running with elevated privileges.
    • Use a reverse proxy: Since gevent should not run as root, it cannot bind to privileged ports like 80 or 443. Use a reverse proxy like nginx or apache-httpd in front of the gevent server.
    • Binding to all interfaces: To bind to all external IPs on a non-privileged port, use 0.0.0.0 in 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.