MongoDB#

MongoDB cache backend. For usage details, see Backends: MongoDB.

MongoCache

MongoDB cache backend.

MongoDict

A dictionary-like interface for a MongoDB collection

class requests_cache.backends.mongodb.MongoCache(db_name='http_cache', connection=None, decode_content=True, serializer=None, **kwargs)[source]#

Bases: BaseCache

MongoDB cache backend. By default, responses are only partially serialized into a MongoDB-compatible document format.

Parameters:
clear()#

Delete all items from the cache

close()#

Close any open backend connections

contains(key=None, request=None, url=None)#

Check if the specified request is cached

Parameters:
create_key(request, match_headers=None, **kwargs)#

Create a normalized cache key from a request object

Parameters:
Return type:

str

delete(*keys, expired=False, invalid=False, older_than=None, requests=None, urls=None)#

Remove responses from the cache according one or more conditions.

Parameters:
filter(valid=True, expired=True, invalid=False, older_than=None)#

Get responses from the cache, with optional filters for which responses to include:

Parameters:
  • valid (bool) – Include valid and unexpired responses; set to False to get only expired/invalid/old responses

  • expired (bool) – Include expired responses

  • invalid (bool) – Include invalid responses (as an empty CachedResponse)

  • older_than (Union[None, int, float, str, datetime, timedelta]) – Get responses older than this value, relative to response.created_at

Return type:

Iterator[CachedResponse]

get_response(key, default=None)#

Retrieve a response from the cache, if it exists

Parameters:
  • key (str) – Cache key for the response

  • default – Value to return if key is not in the cache

Return type:

Optional[CachedResponse]

get_ttl()[source]#

Get the currently defined TTL value in seconds, if any

Return type:

Optional[int]

recreate_keys()#

Recreate cache keys for all previously cached responses

remove_expired_responses(expire_after=None)#
Parameters:

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

reset_expiration(expire_after=None)#

Set a new expiration value to set on existing cache items

Parameters:

expire_after (Union[None, int, float, str, datetime, timedelta]) – New expiration value, relative to the current time

save_response(response, cache_key=None, expires=None)#

Save a response to the cache

Parameters:
  • cache_key (Optional[str]) – Cache key for this response; will otherwise be generated based on request

  • response (Response) – Response to save

  • expires (Optional[datetime]) – Absolute expiration time for this response

set_ttl(ttl, overwrite=False)[source]#

Create or update a TTL index. Notes:

  • This will have no effect if TTL is already set

  • To overwrite an existing TTL index, use overwrite=True

  • This may take some time to complete, depending on the size of your cache

  • Use ttl=None, overwrite=True to remove the TTL index

Parameters:
update(other)#

Update this cache with the contents of another cache

Parameters:

other (BaseCache) –

urls(**kwargs)#

Get all unique cached URLs. Optionally takes keyword arguments for filter().

Return type:

List[str]

class requests_cache.backends.mongodb.MongoDict(db_name, collection_name='http_cache', connection=None, serializer=<requests_cache.serializers.pipeline.SerializerPipeline object>, **kwargs)[source]#

Bases: BaseStorage

A dictionary-like interface for a MongoDB collection

Parameters:
  • db_name (str) – Database name

  • collection_name (str) – Collection name

  • connection (Optional[MongoClient]) – pymongo.MongoClient object to reuse instead of creating a new one

  • kwargs – Additional keyword arguments for pymongo.MongoClient

  • serializer (Union[str, SerializerPipeline, Stage, None]) –

bulk_delete(keys)[source]#

Delete multiple keys from the cache. Does not raise errors for missing keys.

Parameters:

keys (Iterable[str]) –

clear() None.  Remove all items from D.[source]#
close()[source]#

Close any open backend connections

deserialize(key, value)#

Deserialize a value, if a serializer is available.

If deserialization fails (usually due to a value saved in an older requests-cache version), None will be returned.

Parameters:

value (TypeVar(VT)) –

get(k[, d]) D[k] if k in D, else d.  d defaults to None.#
get_ttl()[source]#

Get the currently defined TTL value in seconds, if any

Return type:

Optional[int]

items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair#

as a 2-tuple; but raise KeyError if D is empty.

serialize(value)#

Serialize a value, if a serializer is available

Parameters:

value (TypeVar(VT)) –

set_ttl(ttl, overwrite=False)[source]#

Create or update a TTL index, and ignore and log any errors due to dropping a nonexistent index or attempting to overwrite without `overwrite=True.

Parameters:
setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
update([E, ]**F) None.  Update D from mapping/iterable E and F.#

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values#