Wrappers // Werkzeug Documentation

# Werkzeug

The Swiss Army Knife For Python Web Developers

## Wrappers

The wrappers are simple request and response objects which you can subclass to do whatever you want them to do. The request object contains the information transmitted by the client (webbrowser) and the response object contains all the information sent back to the browser.

An important detail is that the request object is created with the WSGI environ and will act as high-level proxy whereas the response object is an actual WSGI application.

Like everything else in Werkzeug these objects will work correctly with unicode data. Incoming form data parsed by the response object will be decoded into an unicode object if possible and if it makes sense.

You can import all these objects directly from werkzeug.

### Base Wrappers

These objects implement a common set of operations. They are missing fancy addon functionality like user agent parsing or etag handling. These features are available by mixing in various mixin classes or using Request and Response.

class BaseRequest

  Very basic request object. This does not implement advanced stuff like entity tag parsing or cache controls. The request object is created with the WSGI environment as first argument and will add itself to the WSGI environment as `'werkzeug.request'` unless it’s created with populate_request set to False.

  There are a couple of mixins available that add additional functionality to the request object, there is also a class called Request which subclasses BaseRequest and all the important mixins.

  It’s a good idea to create a custom subclass of the BaseRequest and add missing functionality either via mixins or direct implementation. Here an example for such subclasses:

      from werkzeug import BaseRequest, ETagRequestMixin

      class Request(BaseRequest, ETagRequestMixin):
          pass

  Request objects should be considered read only. Even though the object doesn’t enforce read only access everywhere you should never modify any data on the object itself unless you know exactly what you are doing.

  Per default the request object will assume all the text data is utf-8 encoded. Please refer to the unicode chapter for more details about customizing the behavior.

  Creating Request Objects

  __init__ `(environ, populate_request=True, shallow=False)`

    Per default the request object will be added to the WSGI enviornment as werkzeug.request to support the debugging system. If you don’t want that, set populate_request to False.

    If shallow is True the environment is initialized as shallow object around the environ. Every operation that would modify the environ in any way (such as consuming form data) raises an exception unless the shallow attribute is explicitly set to False. This is useful for middlewares where you don’t want to consume the form data by accident. A shallow request is not populated to the WSGI environment.

  from_values `(path='/', base_url=None, query_string=None, **options)`

    Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object in werkzeug.test that allows to create multipart requests etc.

    This accepts the same options as the create_environ function from the utils module and additionally an environ parameter that can contain values which will override the values from dict returned by create_environ.

    Additionally a dict passed to query_string will be encoded in the request class charset.

    returns: request object

  application `(f)`

    Decorate a function as responder that accepts the request as first argument. This works like the responder decorator but the function is passed the request object as first argument:

        @Request.application
        def my_wsgi_app(request):
            return Response('Hello World!')

  Properties

  path
    The current path requested, relative to the position where the WSGI application is mounted (PATH_INFO). It will contain a leading slash and will be at least a string with a single slash when accessing the URL root.
  script_root
    The root path for the script (SCRIPT_NAME). Does not contain a trailing slash.
  url
    The full URL for the current request.
  base_url
    The current full URL without the query string.
  url_root
    The current URL up to the script root.
  host_url
    The current URL for the host.
  host
    The current hostname, without scheme.
  is_secure
    True if this is an HTTPS request.
  is_multithread
    True if this request was created in a multithreaded environment.
  is_multiprocess
    True if this request was created in a forking environment.
  is_run_once
    True if this request was created on the command line, a CGI script or a similar environment.
  is_xhr
    True if the request was triggered via an JavaScript XMLHttpRequest. This only works with libraries that support the X-Requested-With header and set it to “XMLHttpRequest”. Libraries that do that are prototype, jQuery and Mochikit and probably some more.
  method
    The request method. GET, POST etc.
  args
    A dictionary-like object containing all given HTTP GET parameters. See the MultiDict documentation in the utils section.
  form

    A dictionary-like object containing all given HTTP POST parameters. See the MultiDict documentation in the utils section.

    This dict does not contain uploaded files, see files regarding that.

  values
    An immutable dictionary-like object containing both the args and form values. See the CombinedMultiDict documentation in the utils section.
  cookies
    A dictionary with the submitted cookie values.
  files

    A dictionary-like object containing all uploaded files. Each key in files is the name from the `<input type="file" name="" />`. Each value in files is a Werkzeug FileStorage object with the following members:

    - filename - The name of the uploaded file, as a Python string.
    - type - The content type of the uploaded file.
    - data - The raw content of the uploaded file.
    - read() - Read from the stream.

    Note that files will only contain data if the request method was POST and the `<form>` that posted to the request had `enctype="multipart/form-data"`. It will be empty otherwise.

    See the MultiDict / FileStorage documentation in the utils section for more details about the used data structure.

  environ
    The WSGI environment used to create the request object.
  stream
    The buffered stream with incoming data from the webbrowser if the submitted data was not multipart or URL-encoded form data.
  input_stream
    The input stream provided by the client. Used internally by the form data parser. Reading from this stream must never be mixed with accessing stream, data, files, or form, because then it’s not guaranteed that more data is requested from the client than expected. Never read beyond `environ['CONTENT_LENGTH']`.
  data
    Accessing this the first time reads the whole stream and stores it. Keep in mind that this does not read the whole WSGI input stream like Django does.
  remote_addr
    The remote address for the user that created this request. If the class variable is_behind_proxy is set to True (either by subclassing the process or overriding this variable on the instance) it will try to get the value from the X_HTTP_FORWARDED_FOR header. Keep in mind that this is disabled by default because unless you are really behind a proxy this is a security problem.
  access_route
    If you are behind a proxy server this will list all the IP addresses that take place in the request. The end user IP address is the first one in the list, the last proxy server is the last item in the list. This also works if the is_behind_proxy class variable is set to False.

class BaseResponse

  Base response class. The most important fact about a response object is that it’s a regular WSGI application. It’s initialized with a couple of response parameters (headers, body, status code etc.) and will start a valid WSGI response when called with the environ and start response callable.

  Because it’s a WSGI application itself processing usually ends before the actual response is sent to the server. This helps debugging systems because they can catch all the exceptions before responses are started.

  Here a small example WSGI application that takes advantage of the response objects:

      from werkzeug import BaseResponse as Response

      def index():
          return Response('Index page')

      def application(environ, start_response):
          path = environ.get('PATH_INFO') or '/'
          if path == '/':
              response = index()
          else:
              response = Response('Not Found', status=404)
          return response(environ, start_response)

  Like BaseRequest which object is lacking a lot of functionality implemented in mixins. This gives you a better control about the actual API of your response objects, so you can create subclasses and add custom functionality. A full featured response object is available as Response which implements a couple of useful mixins.

  To enforce a new type of already existing responses you can use the force_type method. This is useful if you’re working with different subclasses of response objects and you want to post process them with a know interface.

  Per default the request object will assume all the text data is utf-8 encoded. Please refer to the unicode chapter for more details about customizing the behavior.

  Creating Response Objects

  __init__ `(response=None, status=None, headers=None, mimetype=None, content_type=None)`

    Response can be any kind of iterable or string. If it’s a string it’s considered being an iterable with one item which is the string passed. Headers can be a list of tuples or a Headers object.

    Special note for mimetype and content_type. For most mime types mimetype and content_type work the same, the difference affects only ‘text’ mimetypes. If the mimetype passed with mimetype is a mimetype starting with text/ it becomes a charset parameter defined with the charset of the response object. In constrast the content_type parameter is always added as header unmodified.

  force_type `(response, environ=None)`

    Enforce that the WSGI response is a response object of the current type. Werkzeug will use the BaseResponse internally in many situations like the exceptions. If you call get_response on an exception you will get back a regular BaseResponse object, even if you are using a custom subclass.

    This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided:

        # convert a Werkzeug response object into an instance of the
        # MyResponseClass subclass.
        response = MyResponseClass.force_type(response)

        # convert any WSGI application into a response object
        response = MyResponseClass.force_type(response, environ)

    This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass.

    Keep in mind that this will modify response objects in place if possible!

  from_app `(app, environ, buffered=False)`
    Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the write() callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering.

  Properties

  response
    The application iterator. If constructed from a string this will be a list, otherwise the object provided as application iterator.
  headers
    A Headers object representing the response headers.
  status
    The response status as string.
  status_code
    The response status as integer.
  data
    When accessed the response iterator is buffered and, encoded and returned as bytestring.
  header_list
    Read only list that contains the current list for the headers in the response encoding.
  is_streamed

    If the response is streamed (the response is not a sequence) this property is True. In this case streamed means that there is no information about the number of iterations. This is usully True if a generator is passed to the response object.

    This is useful for checking before applying some sort of post filtering that should not take place for streamed responses.

  Methods

  iter_encoded `(charset=None)`
    Iter the response encoded with the encoding specified. If no encoding is given the encoding from the class is used. Note that this does not encode data that is already a bytestring.
  set_cookie `(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)`

    Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data too:

    - max_age should be a number of seconds, or None (default) if the

        cookie should last only as long as the client’s browser session.

    - expires should be a datetime object or UNIX timestamp.

    - Use domain if you want to set a cross-domain cookie. For example, `domain=".example.com"` will set a cookie that is readable by the domain `www.example.com`, `foo.example.com` etc. Otherwise, a cookie will only be readable by the domain that set it.

    - path limits the cookie to a given path, per default it will span the whole domain.

  delete_cookie `(key, path='/', domain=None)`
    Delete a cookie. Fails silently if key doesn’t exist.
  fix_headers `(environ)`
    This is automatically called right before the response is started and should fix common mistakes in headers. For example location headers are joined with the root URL here.
  close `()`
    Close the wrapped response if possible.
  freeze `()`
    Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one.
  __call__ `(environ, start_response)`
    Process this response as WSGI application.

### Mixin Classes

Werkzeug also provides helper mixins for various HTTP related functionality such as etags, cache control, user agents etc. When subclassing you can mix those classes in to extend the functionality of the BaseRequest or BaseResponse object. Here a small example for a request object that parses accept headers:

    from werkzeug import BaseRequest, AcceptMixin

    class Request(BaseRequest, AcceptMixin):
        pass

The Request and Response classes subclass the BaseRequest and BaseResponse classes and implement all the mixins Werkzeug provides:

class Request

  Full featured request object implementing the following mixins:

  - AcceptMixin for accept header parsing
  - ETagRequestMixin for etag and cache control handling
  - UserAgentMixin for user agent introspection
  - AuthorizationMixin for http auth handling

class Response

  Full featured response object implementing the following mixins:

  - ETagResponseMixin for etag and cache control handling
  - ResponseStreamMixin to add support for the stream property
  - CommonResponseDescriptorsMixin for various HTTP descriptors
  - WWWAuthenticateMixin for HTTP authentication support

class AcceptMixin

  A mixin for classes with an environ attribute to get and all the HTTP accept headers as Accept objects. This can be mixed in request objects or any other object that has a WSGI environ available as environ.

  accept_mimetypes
    List of mimetypes this client supports.
  accept_charsets
    List of charsets this client supports.
  accept_encodings
    List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.
  accept_languages
    List of languages this client accepts.

  All this properties store Accept objects as documented in the utils section.

class AuthorizationMixin

  Adds an authorization property that represents the parsed value of the Authorization header as Authorization object.

  authorization
    The Authorization object in parsed form.

class ETagRequestMixin

  Add entity tag and cache descriptors to a request object or object with an WSGI environment available as environ. This not only provides access to etags but also to the cache control header.

  cache_control
    A CacheControl object for the incoming cache control headers.
  if_match
    An object containing all the etags in the If-Match header.
  if_none_match
    An object containing all the etags in the If-None-Match header.
  if_modified_since
    The parsed If-Modified-Since header as datetime object.
  if_unmodified_since
    The parsed If-Unmodified-Since header as datetime object.

  All the used data structures are documented in the utils section.

class ETagResponseMixin

  Adds extra functionality to a response object for etag and cache handling. This mixin requires an object with at least a headers object that implements a dict like interface similar to Headers.

  cache_control
    The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
  make_conditional `(request_or_environ)`

    Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set.

    This does nothing if the request method in the request or enviorn is anything but GET or HEAD.

    It does not remove the body of the response because that’s something the __call__ function does for us automatically.

    Returns self so that you can do `return resp.make_conditional(req)` but modifies the object in-place.

  add_etag `(overwrite=False, weak=False)`
    Add an etag for the current response if there is none yet.
  set_etag `(etag, weak=False)`
    Set the etag, and override the old one if there was one.
  get_etag `()`
    Return a tuple in the form `(etag, is_weak)`. If there is no ETag the return value is `(None, None)`.
  freeze `(no_etag=False)`
    Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless no_etag is set to True.

class ResponseStreamMixin

  Mixin for BaseRequest subclasses. Classes that inherit from this mixin will automatically get a stream property that provides a write-only interface to the response iterable.

  stream
    The response iterable as write-only stream.

class CommonResponseDescriptorsMixin

  A mixin for BaseResponse subclasses. Response objects that mix this class in will automatically get descriptors for a couple of HTTP headers with automatic type conversion.

  mimetype
    The mimetype (content type without charset etc.)
  location
    The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource.
  age

    The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server.

    Age values are non-negative decimal integers, representing time in seconds.

  content_type
    The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
  content_length
    The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
  content_location
    The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI.
  content_encoding
    The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
  content_language
    The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.
  content_md5
    The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
  date
    The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
  expires
    The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache.
  last_modified
    The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.
  retry_after

    The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client.

    Time in seconds until expiration or date.

  vary
    The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation.
  allow
    The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response.

class WWWAuthenticateMixin

  Adds a www_authenticate property to a response object.

  www_authenticate
    The `WWW-Authenticate` header in a parsed form.

class UserAgentMixin

  Adds a user_agent attribute to the request object which contains the parsed user agent of the browser that triggered the request as UserAgent object.

  user_agent
    The current user agent.

### Note on File Uploads

File uploads are a tricky thing in general. Per default all the file uploads go into temporary files on the filesystem and not the memory of the current process to avoid high memory usage. You could also change that to store the data somewhere else by implementing an object that implements the python IO protocol (see StringIO) for both writing and reading.

Then you have to subclass a request object and override _get_file_stream:

_get_file_stream `()`

  Called to get a stream for the file upload.

  This must provide a file-like class with read(), readline() and seek() methods that is both writeable and readable.

  The default implementation returns a temporary file.