(mongodb)=
MongoDB is a NoSQL document database. It stores data in collections of documents, which are more flexible and less strictly structured than tables in a relational database.
MongoDB scales well and is a good option for larger applications. For raw caching performance, it is not quite as fast as {py:mod}~requests_cache.backends.redis, but may be preferable if you already have an instance running, or if it has a specific feature you want to use. See sections below for some relevant examples.
Initialize with a {py:class}.MongoCache instance:
>>> from requests_cache import CachedSession, MongoCache >>> session = CachedSession(backend=MongoCache())
Or by alias:
>>> session = CachedSession(backend='mongodb')
This backend accepts any keyword arguments for {py:class}pymongo.mongo_client.MongoClient:
>>> backend = MongoCache(host='192.168.1.63', port=27017) >>> session = CachedSession('http_cache', backend=backend)
By default, responses are only partially serialized so they can be saved as plain MongoDB documents. Response data can be easily viewed via the MongoDB shell, Compass, or any other interface for MongoDB.
Here is an example response viewed in MongoDB for VSCode:
:::{dropdown} Screenshot :animate: fade-in-slide-down :color: primary :icon: file-media
:::
MongoDB natively supports TTL, and can automatically remove expired responses from the cache.
Notes:
expiration settings <expiration>.conditional-requests or stale_if_error, you can set TTL to a larger value than your session expire_after, or disable it altogether.Examples: Create a TTL index:
>>> backend = MongoCache() >>> backend.set_ttl(3600)
Overwrite it with a new value:
>>> backend = MongoCache() >>> backend.set_ttl(timedelta(days=1), overwrite=True)
Remove the TTL index:
>>> backend = MongoCache() >>> backend.set_ttl(None, overwrite=True)
Use both MongoDB TTL and requests-cache expiration:
>>> ttl = timedelta(days=1) >>> backend = MongoCache() >>> backend.set_ttl(ttl) >>> session = CachedSession(backend=backend, expire_after=ttl)
Recommended: Set MongoDB TTL to a longer value than your {py:class}.CachedSession expiration. This allows expired responses to be eventually cleaned up, but still be reused for conditional requests for some period of time:
>>> backend = MongoCache() >>> backend.set_ttl(timedelta(days=7)) >>> session = CachedSession(backend=backend, expire_after=timedelta(days=1))