class documentation

class Response(_SansIOResponse):

Known subclasses: werkzeug.test.TestResponse, werkzeug.wrappers.base_response.BaseResponse

View In Hierarchy

Represents an outgoing WSGI HTTP response with body, status, and headers. Has properties and methods for using the functionality defined by various HTTP specs.

The response body is flexible to support different use cases. The simple form is passing bytes, or a string which will be encoded as UTF-8. Passing an iterable of bytes or strings makes this a streaming response. A generator is particularly useful for building a CSV file in memory or using SSE (Server Sent Events). A file-like object is also iterable, although the ~werkzeug.utils.send_file helper should be used in that case.

The response object is itself a WSGI application callable. When called (__call__) with environ and start_response, it will pass its status and headers to start_response then return its body as an iterable.

from werkzeug.wrappers.response import Response

def index():
    return Response("Hello, World!")

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)
Changed in version 2.0: Combine BaseResponse and mixins into a single Response class. Using the old classes is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.5: The direct_passthrough parameter was added.
Parameters
responseThe data for the body of the response. A string or bytes, or tuple or list of strings or bytes, for a fixed-length response, or any other iterable of strings or bytes for a streaming response. Defaults to an empty body.
statusThe status code for the response. Either an int, in which case the default status message is added, or a string in the form {code} {message}, like 404 Not Found. Defaults to 200.
headersA ~werkzeug.datastructures.Headers object, or a list of (key, value) tuples that will be converted to a Headers object.
mimetypeThe mime type (content type without charset or other parameters) of the response. If the value starts with text/ (or matches some other special cases), the charset will be added to create the content_type.
content​_typeThe full content type of the response. Overrides building the value from mimetype.
direct​_passthroughPass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use ~werkzeug.utils.send_file instead of setting this manually.
Class Method force​_type No summary
Class Method from​_app No summary
Method __call__ Process this response as WSGI application.
Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Undocumented
Method __repr__ Undocumented
Method add​_etag Add an etag for the current response if there is none yet.
Method calculate​_content​_length Returns the content length if available or None otherwise.
Method call​_on​_close No summary
Method close Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
Method freeze Make the response object ready to be pickled. Does the following:
Method get​_app​_iter Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response.
Method get​_data The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.
Method get​_json Parse data as JSON. Useful during testing.
Method get​_wsgi​_headers No summary
Method get​_wsgi​_response No summary
Method iter​_encoded No summary
Method make​_conditional No summary
Method make​_sequence No summary
Method set​_data Sets a new string as response. The value must be a string or bytes. If a string is set it's encoded to the charset of the response (utf-8 by default).
Class Variable autocorrect​_location​_header Undocumented
Class Variable automatically​_set​_content​_length Undocumented
Class Variable data Undocumented
Class Variable implicit​_sequence​_conversion Undocumented
Instance Variable content​_range Undocumented
Instance Variable direct​_passthrough Undocumented
Instance Variable response Undocumented
Instance Variable status​_code Undocumented
Property is​_sequence If the iterator is buffered, this property will be True. A response object will consider an iterator to be buffered if the response attribute is a list or tuple.
Property is​_streamed No summary
Property json The parsed JSON data if mimetype indicates JSON (:mimetype:`application/json`, see is_json).
Property stream The response iterable as write-only stream.
Method ​_ensure​_sequence This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list.
Method ​_is​_range​_request​_processable Return True if Range header is present and if underlying resource is considered unchanged when compared with If-Range header.
Method ​_process​_range​_request No summary
Method ​_wrap​_range​_response Wrap existing Response in case of Range Request context.
Instance Variable ​_on​_close Undocumented
@classmethod
def force_type(cls, response, environ=None):

Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response on an exception you will get back a regular Response 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!

Parameters
response:Responsea response object or wsgi application.
environ:t.Optional[WSGIEnvironment]a WSGI environment object.
Returns
Responsea response object.
@classmethod
def from_app(cls, 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.
Parameters
app:WSGIApplicationthe WSGI application to execute.
environ:WSGIEnvironmentthe WSGI environment to execute against.
buffered:boolset to True to enforce buffering.
Returns
Responsea response object.
def __call__(self, environ, start_response):
Process this response as WSGI application.
Parameters
environ:WSGIEnvironmentthe WSGI environment.
start​_response:StartResponsethe response callable provided by the WSGI server.
Returns
t.Iterable[bytes]an application iterator
def __enter__(self):

Undocumented

Returns
ResponseUndocumented
def __exit__(self, exc_type, exc_value, tb):

Undocumented

def __init__(self, response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False):

Undocumented

Parameters
response:t.Optional[t.Union[t.Iterable[bytes], bytes, t.Iterable[str], str]]Undocumented
status:t.Optional[t.Union[int, str, HTTPStatus]]Undocumented
headers:t.Optional[t.Union[t.Mapping[str, t.Union[str, int, t.Iterable[t.Union[str, int]]]], t.Iterable[t.Tuple[str, t.Union[str, int]]]]]Undocumented
mimetype:t.Optional[str]Undocumented
content​_type:t.Optional[str]Undocumented
direct​_passthrough:boolUndocumented
def __repr__(self):

Undocumented

Returns
strUndocumented
def add_etag(self, overwrite=False, weak=False):

Add an etag for the current response if there is none yet.

Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be available in some environments.
Parameters
overwrite:boolUndocumented
weak:boolUndocumented
def calculate_content_length(self):
Returns the content length if available or None otherwise.
Returns
t.Optional[int]Undocumented
def call_on_close(self, func):

Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator.

New in version 0.6.
Parameters
func:t.Callable[[], t.Any]Undocumented
Returns
t.Callable[[], t.Any]Undocumented
def close(self):

Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.

New in version 0.9: Can now be used in a with statement.
def freeze(self, no_etag=None):

Make the response object ready to be pickled. Does the following:

  • Buffer the response into a list, ignoring implicity_sequence_conversion and direct_passthrough.
  • Set the Content-Length header.
  • Generate an ETag header if one is not already set.
Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.6: The Content-Length header is set.
Parameters
no​_etag:NoneUndocumented
def get_app_iter(self, environ):

Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response.

If the request method is HEAD or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned.

New in version 0.6.
Parameters
environ:WSGIEnvironmentthe WSGI environment of the request.
Returns
t.Iterable[bytes]a response iterable.
def get_data(self, as_text=False):

The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.

This behavior can be disabled by setting implicit_sequence_conversion to False.

If as_text is set to True the return value will be a decoded string.

New in version 0.9.
Parameters
as​_text:boolUndocumented
Returns
t.Union[bytes, str]Undocumented
def get_json(self, force=False, silent=False):

Parse data as JSON. Useful during testing.

If the mimetype does not indicate JSON (:mimetype:`application/json`, see is_json), this returns None.

Unlike Request.get_json, the result is not cached.

Parameters
force:boolIgnore the mimetype and always try to parse JSON.
silent:boolSilence parsing errors and return None instead.
Returns
t.Optional[t.Any]Undocumented
def get_wsgi_headers(self, environ):

This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary.

For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes.

Changed in version 0.6: Previously that function was called fix_headers and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly.

Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered.

Parameters
environ:WSGIEnvironmentthe WSGI environment of the request.
Returns
Headersreturns a new ~werkzeug.datastructures.Headers object.
def get_wsgi_response(self, environ):

Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is 'HEAD' the response will be empty and only the headers and status code will be present.

New in version 0.6.
Parameters
environ:WSGIEnvironmentthe WSGI environment of the request.
Returns
t.Tuple[t.Iterable[bytes], str, t.List[t.Tuple[str, str]]]an (app_iter, status, headers) tuple.
def iter_encoded(self):
Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless direct_passthrough was activated.
Returns
t.Iterator[bytes]Undocumented
def make_conditional(self, request_or_environ, accept_ranges=False, complete_length=None):

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 environ is anything but GET or HEAD.

For optimal performance when handling range requests, it's recommended that your response data object implements seekable, seek and tell methods as described by io.IOBase. Objects returned by ~werkzeug.wsgi.wrap_file automatically implement those methods.

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.

Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.
Parameters
request​_or​_environ:t.Union[WSGIEnvironment, Request]a request object or WSGI environment to be used to make the response conditional against.
accept​_ranges:t.Union[bool, str]This parameter dictates the value of Accept-Ranges header. If False (default), the header is not set. If True, it will be set to "bytes". If None, it will be set to "none". If it's a string, it will use this value.
complete​_length:t.Optional[int]Will be used only in valid Range Requests. It will set Content-Range complete length value and compute Content-Length real value. This parameter is mandatory for successful Range Requests completion.
Returns
ResponseUndocumented
Raises
Unknown exception~werkzeug.exceptions.RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.
def make_sequence(self):

Converts the response iterator in a list. By default this happens automatically if required. If implicit_sequence_conversion is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items.

New in version 0.6.
def set_data(self, value):

Sets a new string as response. The value must be a string or bytes. If a string is set it's encoded to the charset of the response (utf-8 by default).

New in version 0.9.
Parameters
value:t.Union[bytes, str]Undocumented
autocorrect_location_header: bool =

Undocumented

automatically_set_content_length: bool =

Undocumented

data =

Undocumented

implicit_sequence_conversion: bool =

Undocumented

content_range =

Undocumented

direct_passthrough =

Undocumented

response =

Undocumented

status_code: int =

Undocumented

@property
is_sequence: bool =

If the iterator is buffered, this property will be True. A response object will consider an iterator to be buffered if the response attribute is a list or tuple.

New in version 0.6.
@property
is_streamed: bool =

If the response is streamed (the response is not an iterable with a length information) this property is True. In this case streamed means that there is no information about the number of iterations. This is usually 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.

@property
json: t.Optional[t.Any] =

The parsed JSON data if mimetype indicates JSON (:mimetype:`application/json`, see is_json).

Calls get_json with default arguments.

The response iterable as write-only stream.
def _ensure_sequence(self, mutable=False):

This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list.

New in version 0.6.
Parameters
mutable:boolUndocumented
def _is_range_request_processable(self, environ):
Return True if Range header is present and if underlying resource is considered unchanged when compared with If-Range header.
Parameters
environ:WSGIEnvironmentUndocumented
Returns
boolUndocumented
def _process_range_request(self, environ, complete_length=None, accept_ranges=None):

Handle Range Request related headers (RFC7233). If Accept-Ranges header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a RangeWrapper.

Returns True if Range Request can be fulfilled, False otherwise.

Changed in version 2.0: Returns False if the length is 0.
Parameters
environ:WSGIEnvironmentUndocumented
complete​_length:t.Optional[int]Undocumented
accept​_ranges:t.Optional[t.Union[bool, str]]Undocumented
Returns
boolUndocumented
Raises
Unknown exception~werkzeug.exceptions.RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.
def _wrap_range_response(self, start, length):
Wrap existing Response in case of Range Request context.
Parameters
start:intUndocumented
length:intUndocumented
_on_close: t.List[t.Callable[[], t.Any]] =

Undocumented