Response#

class requests_cache.models.response.BaseResponse(created_at=_Nothing.NOTHING, expires=None)[source]#

Bases: Response

Wrapper class for responses returned by CachedSession. This mainly exists to provide type hints for extra cache-related attributes that are added to non-cached responses.

Parameters:
property apparent_encoding#

The apparent encoding, provided by the charset_normalizer or chardet libraries.

cache_key: str = ''#
close()#

Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.

Note: Should not normally need to be called explicitly.

property content#

Content of the response, in bytes.

cookies#

A CookieJar of Cookies the server sent back.

created_at: datetime#
elapsed#

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

encoding#

Encoding to decode with when accessing r.text.

expires: Optional[datetime]#
property from_cache: bool#
headers#

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history#

A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.

property is_expired: bool#
property is_permanent_redirect#

True if this Response one of the permanent versions of redirect.

property is_redirect#

True if this Response is a well-formed HTTP redirect that could have been processed automatically (by Session.resolve_redirects()).

iter_content(chunk_size=1, decode_unicode=False)#

Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.

chunk_size must be of type int or None. A value of None will function differently depending on the value of stream. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk.

If decode_unicode is True, content will be decoded using the best available encoding based on the response.

iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)#

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

Note

This method is not reentrant safe.

json(**kwargs)#

Returns the json-encoded content of a response, if any.

Parameters:

**kwargs – Optional arguments that json.loads takes.

Raises:

requests.exceptions.JSONDecodeError – If the response body does not contain valid json.

Returns the parsed header links of the response, if any.

property next#

Returns a PreparedRequest for the next request in a redirect chain, if there is one.

property ok#

Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

raise_for_status()#

Raises HTTPError, if one occurred.

raw#

File-like object representation of response (for advanced usage). Use of raw requires that stream=True be set on the request. This requirement does not apply for use internally to Requests.

reason#

Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.

request#

The PreparedRequest object to which this is a response.

revalidated: bool = False#
status_code#

Integer Code of responded HTTP Status, e.g. 404 or 200.

property text#

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using charset_normalizer or chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

url#

Final URL location of Response.

class requests_cache.models.response.CachedResponse(content=None, decoded_content=None, next=None, cookies=_Nothing.NOTHING, created_at=None, elapsed=_Nothing.NOTHING, encoding=None, expires=None, headers=_Nothing.NOTHING, history=_Nothing.NOTHING, reason=None, request=_Nothing.NOTHING, status_code=0, url=None)[source]#

Bases: RichMixin, BaseResponse

A class that emulates requests.Response, optimized for serialization

Parameters:
property apparent_encoding#

The apparent encoding, provided by the charset_normalizer or chardet libraries.

cache_key: str = ''#
close()#

Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.

Note: Should not normally need to be called explicitly.

property content#

Content of the response, in bytes.

cookies: RequestsCookieJar#

A CookieJar of Cookies the server sent back.

created_at: datetime#
elapsed: timedelta#

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

encoding: str#

Encoding to decode with when accessing r.text.

expires: Optional[datetime]#
property expires_delta: Optional[int]#

Get time to expiration in seconds (rounded to the nearest second)

property expires_unix: Optional[int]#

Get expiration time as a Unix timestamp

property from_cache: bool#
classmethod from_response(response, **kwargs)[source]#

Create a CachedResponse based on an original Response or another CachedResponse object

Parameters:

response (Response) –

Return type:

CachedResponse

headers: CaseInsensitiveDict#

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history: List[CachedResponse]#

A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.

property is_expired: bool#

Determine if this cached response is expired

is_older_than(older_than)[source]#

Determine if this cached response is older than the given time

Parameters:

older_than (Union[None, int, float, str, datetime, timedelta]) –

Return type:

bool

property is_permanent_redirect#

True if this Response one of the permanent versions of redirect.

property is_redirect#

True if this Response is a well-formed HTTP redirect that could have been processed automatically (by Session.resolve_redirects()).

iter_content(chunk_size=1, decode_unicode=False)#

Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.

chunk_size must be of type int or None. A value of None will function differently depending on the value of stream. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk.

If decode_unicode is True, content will be decoded using the best available encoding based on the response.

iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)#

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

Note

This method is not reentrant safe.

json(**kwargs)#

Returns the json-encoded content of a response, if any.

Parameters:

**kwargs – Optional arguments that json.loads takes.

Raises:

requests.exceptions.JSONDecodeError – If the response body does not contain valid json.

Returns the parsed header links of the response, if any.

property next: Optional[PreparedRequest]#

Returns a PreparedRequest for the next request in a redirect chain, if there is one.

property ok#

Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

raise_for_status()#

Raises HTTPError, if one occurred.

raw: CachedHTTPResponse = None#

File-like object representation of response (for advanced usage). Use of raw requires that stream=True be set on the request. This requirement does not apply for use internally to Requests.

reason: str#

Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.

request: CachedRequest#

The PreparedRequest object to which this is a response.

reset_expiration(expire_after)[source]#

Set a new expiration for this response

Parameters:

expire_after (Union[None, int, float, str, datetime, timedelta]) –

revalidated: bool = False#
property size: int#

Get the size of the response body in bytes

status_code: int#

Integer Code of responded HTTP Status, e.g. 404 or 200.

property text#

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using charset_normalizer or chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

url: str#

Final URL location of Response.

class requests_cache.models.response.OriginalResponse(**kwargs)[source]#

Bases: BaseResponse

Wrapper class for non-cached responses returned by CachedSession

property apparent_encoding#

The apparent encoding, provided by the charset_normalizer or chardet libraries.

cache_key: str = ''#
close()#

Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.

Note: Should not normally need to be called explicitly.

property content#

Content of the response, in bytes.

cookies#

A CookieJar of Cookies the server sent back.

created_at: datetime#
elapsed#

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

encoding#

Encoding to decode with when accessing r.text.

expires: Optional[datetime]#
property from_cache: bool#
headers#

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history#

A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.

property is_expired: bool#
property is_permanent_redirect#

True if this Response one of the permanent versions of redirect.

property is_redirect#

True if this Response is a well-formed HTTP redirect that could have been processed automatically (by Session.resolve_redirects()).

iter_content(chunk_size=1, decode_unicode=False)#

Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.

chunk_size must be of type int or None. A value of None will function differently depending on the value of stream. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk.

If decode_unicode is True, content will be decoded using the best available encoding based on the response.

iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)#

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

Note

This method is not reentrant safe.

json(**kwargs)#

Returns the json-encoded content of a response, if any.

Parameters:

**kwargs – Optional arguments that json.loads takes.

Raises:

requests.exceptions.JSONDecodeError – If the response body does not contain valid json.

Returns the parsed header links of the response, if any.

property next#

Returns a PreparedRequest for the next request in a redirect chain, if there is one.

property ok#

Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

raise_for_status()#

Raises HTTPError, if one occurred.

raw#

File-like object representation of response (for advanced usage). Use of raw requires that stream=True be set on the request. This requirement does not apply for use internally to Requests.

reason#

Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.

request#

The PreparedRequest object to which this is a response.

revalidated: bool = False#
status_code#

Integer Code of responded HTTP Status, e.g. 404 or 200.

property text#

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using charset_normalizer or chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

url#

Final URL location of Response.

classmethod wrap_response(response, actions)[source]#

Modify a response object in-place and add extra cache-related attributes

Parameters:
Return type:

OriginalResponse

requests_cache.models.response.format_datetime(value)[source]#

Get a formatted datetime string in the local time zone

Parameters:

value (Optional[datetime]) –

Return type:

str

requests_cache.models.response.format_file_size(n_bytes)[source]#

Convert a file size in bytes into a human-readable format

Parameters:

n_bytes (int) –

Return type:

str