class Response(_SansIOResponse):
Known subclasses: werkzeug.test.TestResponse
, werkzeug.wrappers.base_response.BaseResponse
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)
Parameters | |
response | The 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. |
status | The 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. |
headers | A ~werkzeug.datastructures.Headers object,
or a list of (key, value) tuples that will be converted to a
Headers object. |
mimetype | The 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_type | The full content type of the response. Overrides building the value from mimetype. |
direct_passthrough | Pass 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 |
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:Response | a response object or wsgi application. |
environ:t.Optional[ | a WSGI environment object. |
Returns | |
Response | a response object. |
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:WSGIApplication | the WSGI application to execute. |
environ:WSGIEnvironment | the WSGI environment to execute against. |
buffered:bool | set to True to enforce buffering. |
Returns | |
Response | a response object. |
Parameters | |
environ:WSGIEnvironment | the WSGI environment. |
start_response:StartResponse | the response callable provided by the WSGI server. |
Returns | |
t.Iterable[ | an application iterator |
Undocumented
Parameters | |
response:t.Optional[ | Undocumented |
status:t.Optional[ | Undocumented |
headers:t.Optional[ | Undocumented |
mimetype:t.Optional[ | Undocumented |
content_type:t.Optional[ | Undocumented |
direct_passthrough:bool | Undocumented |
Add an etag for the current response if there is none yet.
Parameters | |
overwrite:bool | Undocumented |
weak:bool | Undocumented |
None
otherwise.Returns | |
t.Optional[ | Undocumented |
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.
Parameters | |
func:t.Callable[ | Undocumented |
Returns | |
t.Callable[ | Undocumented |
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
Make the response object ready to be pickled. Does the following:
implicity_sequence_conversion
and
direct_passthrough
.Parameters | |
no_etag:None | Undocumented |
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.
Parameters | |
environ:WSGIEnvironment | the WSGI environment of the request. |
Returns | |
t.Iterable[ | a response iterable. |
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.
Parameters | |
as_text:bool | Undocumented |
Returns | |
t.Union[ | Undocumented |
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:bool | Ignore the mimetype and always try to parse JSON. |
silent:bool | Silence parsing errors and return None instead. |
Returns | |
t.Optional[ | Undocumented |
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:WSGIEnvironment | the WSGI environment of the request. |
Returns | |
Headers | returns a new ~werkzeug.datastructures.Headers
object. |
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.
Parameters | |
environ:WSGIEnvironment | the WSGI environment of the request. |
Returns | |
t.Tuple[ | an (app_iter, status, headers) tuple. |
direct_passthrough
was activated.Returns | |
t.Iterator[ | Undocumented |
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.
Parameters | |
request_or_environ:t.Union[ | a request object or WSGI environment to be used to make the response conditional against. |
accept_ranges:t.Union[ | 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[ | 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 | |
Response | Undocumented |
Raises | |
Unknown exception | ~werkzeug.exceptions.RequestedRangeNotSatisfiable
if Range header could not be parsed or satisfied. |
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.
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).
Parameters | |
value:t.Union[ | Undocumented |
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.
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.
t.Optional[ t.Any]
=
The parsed JSON data if mimetype
indicates JSON
(:mimetype:`application/json`, see is_json
).
Calls get_json
with default arguments.
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.
Parameters | |
mutable:bool | Undocumented |
Range
header is present and if underlying
resource is considered unchanged when compared with If-Range
header.Parameters | |
environ:WSGIEnvironment | Undocumented |
Returns | |
bool | Undocumented |
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.
Parameters | |
environ:WSGIEnvironment | Undocumented |
complete_length:t.Optional[ | Undocumented |
accept_ranges:t.Optional[ | Undocumented |
Returns | |
bool | Undocumented |
Raises | |
Unknown exception | ~werkzeug.exceptions.RequestedRangeNotSatisfiable
if Range header could not be parsed or satisfied. |