Response Objects โ
class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False) โ
The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you donโt have to create this object yourself because make_response() will take care of that for you.
If you want to replace the response object used you can subclass this and set response_class to your subclass.
Changelog
Changed in version 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON.
Changed in version 1.0: Added max_cookie_size.
Parameters:
response (Iterable[str] | Iterable[bytes])โstatus (int | str | HTTPStatus | None)โheaders (Headers)โmimetype (str | None)โcontent_type (str | None)โdirect_passthrough (bool)โ
accept_ranges โ
The
Accept-Rangesheader. Even though the name would indicate that multiple values are supported, it must be one string token only.The values
'bytes'and'none'are common.Changelog
New in version 0.7.
propertyaccess_control_allow_credentials:boolโWhether credentials can be shared by the browser to JavaScript code. As part of the preflight request it indicates whether credentials can be used on the cross origin request.
access_control_allow_headers โ
Which headers can be sent with the cross origin request.
access_control_allow_methods โ
Which methods can be used for the cross origin request.
access_control_allow_origin โ
The origin or
โ*โfor any origin that may make cross origin requests.access_control_expose_headers โ
Which headers can be shared by the browser to JavaScript code.
access_control_max_age โ
The maximum age in seconds the access control settings can be cached for.
add_etag(
overwrite=False, weak=False) โAdd an etag for the current response if there is none yet.
Changelog
Changed in version 2.0:
SHA-1is used to generate the value.MD5may not be available in some environments.Parameters:
overwrite (bool)โweak (bool)โ
Return type:
Noneage โ
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.
propertyallow:HeaderSetโ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.autocorrect_location_header =
FalseโIf a redirect
Locationheader is a relative URL, make it an absolute URL, including scheme and domain.Changelog
Changed in version 2.1: This is disabled by default, so responses will send relative redirects.
New in version 0.8.
automatically_set_content_length =
TrueโShould this response object automatically set the content-length header if possible? This is true by default.
Changelog
New in version 0.8.
propertycache_control:ResponseCacheControlโThe
Cache-Controlgeneral-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.calculate_content_length() โ
Returns the content length if available or
Noneotherwise.Return type:
int | Nonecall_on_close(
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.
Changelog
New in version 0.6.
Parameters:
func (Callable[[], Any])โ
Return type:
Callable[[], Any]propertycharset:strโThe charset used to encode body and cookie data. Defaults to
UTF-8.Deprecated since version 2.3: Will be removed in
Werkzeug3.0. Response data must always beUTF-8.close() โ
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
Changelog
New in version 0.9: Can now be used in a
withstatement.Return type:
Nonecontent_encoding โ
The
Content-Encodingentity-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 theContent-Typeheader field.propertycontent_language:HeaderSetโThe
Content-Languageentity-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_length โ
The
Content-Lengthentity-header field indicates the size of the entity-body, in decimal number ofOCTETs, sent to the recipient or, in the case of theHEADmethod, the size of the entity-body that would have been sent had the request been aGET.content_location โ
The
Content-Locationentity-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_md5 โ
The
Content-MD5entity-header field, as defined inRFC 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.)propertycontent_range:ContentRangeโThe
Content-Rangeheader as aContentRangeobject. Available even if the header is not set.Changelog
New in version 0.7.
propertycontent_security_policy:ContentSecurityPolicyโThe
Content-Security-Policyheader as aContentSecurityPolicyobject. Available even if the header is not set.The
Content-Security-Policyheader adds an additional layer of security to help detect and mitigate certain types of attacks.propertycontent_security_policy_report_only:ContentSecurityPolicyโThe
Content-Security-policy-report-onlyheader as a ContentSecurityPolicy object. Available even if the header is not set.The
Content-Security-Policy-Report-Onlyheader adds acsppolicy that is not enforced but is reported thereby helping detect certain types of attacks.content_type โ
The
Content-Typeentity-header field indicates the media type of the entity-body sent to the recipient or, in the case of theHEADmethod, the media type that would have been sent had the request been aGET.cross_origin_embedder_policy โ
Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the
werkzeug.http.COEPenum.cross_origin_opener_policy โ
Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the
werkzeug.http.COOPenum.propertydata:bytes | strโA descriptor that calls
get_data()andset_data().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.Changelog
Changed in version 2.0: The datetime object is timezone-aware.
default_mimetype:
str | None = 'text/html'โthe default mimetype if none is provided.
default_status =
200โthe default status if none is provided.
delete_cookie(
key, path='/', domain=None, secure=False, httponly=False, samesite=None) โDelete a cookie. Fails silently if key doesnโt exist.
Parameters:
key (str)โ the key (name) of the cookie to be deleted.path (str | None)โ if the cookie that should be deleted was limited to a path, the path has to be defined here.domain (str | None)โ if the cookie that should be deleted was limited to a domain, that domain has to be defined here.secure (bool)โ IfTrue, the cookie will only be available viaHTTPS.httponly (bool)โ Disallow JavaScript access to the cookie.samesite (str | None)โ Limit the scope of the cookie to only be attached to requests that are โsame-siteโ.
Return type:
Nonedirect_passthrough โ
Pass the response body directly through as the
WSGIiterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Usesend_file()instead of setting this manually.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.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
classmethodforce_type(response, environ=None) โEnforce that the
WSGIresponse is a response object of the current type. Werkzeug will use theResponseinternally in many situations like the exceptions. If you callget_response()on an exception you will get back a regularResponseobject, even if you are using a custom subclass.This method can enforce a given response type, and it will also convert arbitrary
WSGIcallables into response objects if an environ is provided:python# 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)# 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 (WSGIEnvironment | None)โ aWSGIenvironment object.
Returns: a response object.
Return type:
Responsefreeze() โ
Make the response object ready to be pickled. Does the following:
Buffer the response into a list, ignoring
implicity_sequence_conversionanddirect_passthrough.Set the
Content-Lengthheader.Generate an
ETagheader if one is not already set.
Changelog
Changed in version 2.1: Removed the
no_etagparameter.Changed in version 2.0: An
ETagheader is always added.Changed in version 0.6: The
Content-Lengthheader is set.Return type:
Noneclassmethod 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 thestart_responsefunction. This tries to resolve such edge cases automatically. But if you donโt get the expected output you should set buffered toTruewhich 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: a response object.
Return type:
Responseget_app_iter(
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
HEADor the status code is in a range where theHTTPspecification requires an empty response, an empty iterable is returned.Changelog
New in version 0.6.
Parameters:
environ (WSGIEnvironment)โ theWSGIenvironment of the request.
Returns: a response iterable.
Return type:
t.Iterable[bytes]get_data(
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_conversiontoFalse.If
as_textis set toTruethe return value will be a decoded string.Changelog
New in version 0.9.
Parameters:
as_text (bool)โ
Return type:
bytes | strget_etag() โ
Return a tuple in the form
(etag, is_weak). If there is noETagthe return value is(None, None).Return type:
tuple[str, bool] | tuple[None, None]get_json(
force=False, silent=False) โParse
dataasJSON. Useful during testing.If the mimetype does not indicate JSON (
application/json, seeis_json), this returns None.Unlike
Request.get_json(), the result is not cached.Parameters:
force (bool)โ Ignore the mimetype and always try to parseJSON.silent (bool)โ Silence parsing errors and returnNoneinstead.
Return type:
Any | Noneget_wsgi_headers(
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.
Changelog
Changed in version 0.6: Previously that function was called
fix_headersand 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)โ theWSGIenvironment of the request.
Returns: returns a new
Headersobject.Return type:
Headersget_wsgi_response(
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.Changelog
New in version 0.6.
Parameters:
environ (WSGIEnvironment)โ theWSGIenvironment of the request.
Returns: an
(app_iter, status, headers)tuple.Return type:
tuple[t.Iterable[bytes], str, list[tuple[str, str]]]implicit_sequence_conversion =
Trueโif set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list.
Changelog
New in version 0.6.2: That attribute was previously called
implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.propertyis_json:boolโCheck if the mimetype indicates JSON data, either
application/jsonorapplication/*+json.propertyis_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.
Changelog
New in version 0.6.
propertyis_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.
iter_encoded() โ
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_passthroughwas activated.Return type:
Iterator[bytes]propertyjson:Any | NoneโThe parsed JSON data if mimetype indicates JSON (
application/json, seeis_json).Calls
get_json()with default arguments.last_modified โ
The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
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.
make_conditional(
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
GETorHEAD.For optimal performance when handling range requests, itโs recommended that your response data object implements
seekable,seekandtellmethods as described byio.IOBase. Objects returned bywrap_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 (WSGIEnvironment | Request)โ a request object or WSGI environment to be used to make the response conditional against.accept_ranges (bool | str)โ This parameter dictates the value of Accept-Ranges header. IfFalse(default), the header is not set. IfTrue, it will be set to"bytes". If itโs a string, it will use this value.complete_length (int | None)โ Will be used only in valid Range Requests. It will setContent-Rangecomplete length value and computeContent-Lengthreal value. This parameter is mandatory for successful Range Requests completion.
Raises:
RequestedRangeNotSatisfiableifRangeheader could not be parsed or satisfied.Return type:
ResponseChangelog
Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a
416Range Not Satisfiable error.make_sequence() โ
Converts the response iterator in a list. By default this happens automatically if required. If
implicit_sequence_conversionis disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items.Changelog
New in version 0.6.
Return type:
Nonepropertymax_cookie_size:intโRead-only view of the
MAX_COOKIE_SIZEconfig key.See
max_cookie_sizein Werkzeugโs docs.propertymimetype:str | NoneโThe mimetype (content type without charset etc.)
propertymimetype_params:dict[str, str]โThe mimetype parameters as dict. For example if the content type is
text/html; charset=utf-8the params would be{'charset': 'utf-8'}.Changelog
New in version 0.5.
response:
t.Iterable[str] | t.Iterable[bytes]โThe response body to send as the
WSGIiterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes asUTF-8.Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.
propertyretry_after:datetime | Noneโ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.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
set_cookie(
key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None) โSets a cookie.
A warning is raised if the size of the cookie header exceeds
max_cookie_size, but the header will still be set.Parameters:
key (str)โ the key (name) of the cookie to be set.value (str)โ the value of the cookie.max_age (timedelta | int | None)โ should be a number of seconds, orNone(default) if the cookie should last only as long as the clientโs browser session.expires (str | datetime | int | float | None)โ should be a datetime object orUNIXtimestamp.path (str | None)โ limits the cookie to a given path, per default it will span the whole domain.domain (str | None)โ if you want to set a cross-domain cookie. For example,domain=".example.com"will set a cookie that is readable by the domainwww.example.com,foo.example.cometc. Otherwise, a cookie will only be readable by the domain that set it.secure (bool)โ IfTrue, the cookie will only be available viaHTTPS.httponly (bool)โ DisallowJavaScriptaccess to the cookie.samesite (str | None)โ Limit the scope of the cookie to only be attached to requests that are โsame-siteโ.
Return type:
Noneset_data(
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-8by default).Changelog
New in version 0.9.
Parameters:
value (bytes | str)โ
Return type:
Noneset_etag(
etag, weak=False) โSet the etag, and override the old one if there was one.
Parameters:
etag (str)โweak (bool)โ
Return type:
Nonepropertystatus:strโThe
HTTPstatus code as a string.propertystatus_code:intโThe
HTTPstatus code as a number.propertystream:ResponseStreamโThe response iterable as write-only stream.
propertyvary:HeaderSetโ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.
propertywww_authenticate:WWWAuthenticateโThe
WWW-Authenticateheader parsed into aWWWAuthenticateobject. Modifying the object will modify the header value.This header is not set by default. To set this header, assign an instance of
WWWAuthenticateto this attribute.pythonresponse.www_authenticate = WWWAuthenticate( "basic", {"realm": "Authentication Required"} )response.www_authenticate = WWWAuthenticate( "basic", {"realm": "Authentication Required"} )Multiple values for this header can be sent to give the client multiple options. Assign a list to set multiple headers. However, modifying the items in the list will not automatically update the header values, and accessing this attribute will only ever return the first value.
To unset this header, assign
Noneor usedel.Changed in version 2.3: This attribute can be assigned to to set the header. A list can be assigned to set multiple header values. Use del to unset the header.
Changed in version 2.3:
WWWAuthenticateis no longer adict. Thetokenattribute was added for auth challenges that use a token instead of parameters.