Skip to main content

MongoDB backend for cashews

Project description

cashews-mongo

Checks PyPI version

cashews-mongo provides a MongoDB backend for cashews.

What You Get

  • Drop-in Cashews backend registration via import.
  • Support for mongo://, mongodb://, and mongodb+srv:// URLs.
  • Core cache operations: KV, TTL, counters, sets, scans, bits, and locks.
  • Supports Cashews bloom and dual_bloom decorators.
  • Optional local read cache with remote invalidation events.
  • Integration harness that boots MongoDB in replica-set mode.

Installation

Install with pip:

pip install cashews-mongo

For development dependencies:

python -m pip install --group dev .

Quick Start

import asyncio

from cashews import Cache
import cashews_mongo  # registers backend aliases: mongo/mongodb/mongodb+srv


async def main() -> None:
    cache = Cache()
    cache.setup("mongodb://127.0.0.1:27017/cashews/cache")
    await cache.init()

    await cache.set("k", "v", expire=30)
    print(await cache.get("k"))

    await cache.close()


asyncio.run(main())

Connection URL Rules

  • mongo://... is accepted and normalized to mongodb://....
  • URL path format is /<database>/<collection>.
  • If missing, defaults are database=cashews and collection=cache.

Examples:

mongodb://127.0.0.1:27017
mongodb://127.0.0.1:27017/mydb/mycollection
mongo://127.0.0.1:27017/mydb/mycollection
mongodb+srv://user:pass@cluster.example.net/mydb/mycollection

Client-Side (L1) Mode

Enable with client_side=true in the cache URL:

cache.setup("mongodb://127.0.0.1:27017/cashews/cache?client_side=true")

Useful URL options:

  • client_side=true: use MongoClientSideBackend.
  • suppress=true|false: when change-stream listener startup fails, either continue without L1 (true, default) or fail fast (false).
  • local_cache_size=<int>: max entries in local cache.
  • local_cache_check_interval=<seconds>: local cache cleanup cadence.
  • client_side_listen_timeout=<seconds>: listener poll timeout.

Notes:

  • Change streams require replica-set mode.
  • If change streams are unavailable and suppress=true, backend remains usable, but local read cache is disabled.

Bloom Filter Support

cashews-mongo supports Cashews bloom primitives through backend bit operations.

import asyncio

from cashews import Cache
import cashews_mongo  # noqa: F401


async def main() -> None:
    cache = Cache("bloom")
    cache.setup("mongodb://127.0.0.1:27017/cashews/cache")

    @cache.bloom(
        capacity=1000,
        false_positives=1,
        check_false_positive=False,
        name="bf:{value}",
    )
    async def maybe_exists(value: str) -> bool:
        return value == "known"

    @cache.dual_bloom(capacity=1000, false=1, name="dbf:{value}")
    async def maybe_exists_dual(value: str) -> bool:
        return value == "known"

    await cache.init()
    try:
        # bloom: prime positive entries via `.set(...)`
        assert await maybe_exists("known") is False
        await maybe_exists.set("known")  # type: ignore[attr-defined]
        assert await maybe_exists("known") is True

        # dual_bloom: first call learns, second call is usually served by bloom state
        assert await maybe_exists_dual("known") is True
        assert await maybe_exists_dual("known") is True
    finally:
        await cache.close()


asyncio.run(main())

Direct Backend Usage

from cashews_mongo import MongoBackend, MongoClientSideBackend

backend = MongoBackend(
    uri="mongodb://127.0.0.1:27017",
    database="cashews",
    collection="cache",
)

client_side_backend = MongoClientSideBackend(
    uri="mongodb://127.0.0.1:27017",
    database="cashews",
    collection="cache",
    suppress=False,
)

Development with Pixi

pixi run lint
pixi run test-unit
pixi run test-integration
pixi run test

test-integration runs python scripts/integration.py run, which:

  1. Starts Docker MongoDB.
  2. Initializes a single-node replica set.
  3. Waits for writable primary.
  4. Runs integration tests.
  5. Tears everything down.

Manual harness commands:

pixi run python scripts/integration.py up
pixi run python scripts/integration.py run
pixi run python scripts/integration.py down

Supported env vars:

  • CASHEWS_MONGO_PORT (default 27017)
  • CASHEWS_MONGO_REPLICA_SET (default rs0)

Troubleshooting

  • ModuleNotFoundError: No module named 'pymongo': run commands through project env (pixi run ...) or install deps with python -m pip install --group dev ..
  • Client-side cache disabled unexpectedly: verify MongoDB replica-set mode and listener startup logs.
  • InvalidReplicaSetConfig: ensure compose and harness use the same CASHEWS_MONGO_REPLICA_SET.
  • Docker/compose missing: install Docker and ensure docker compose (or docker-compose) is in PATH.
  • Port conflict on 27017: set CASHEWS_MONGO_PORT (for example 27018).

Project Layout

  • src/cashews_mongo/backend.py: main MongoDB backend.
  • src/cashews_mongo/client_side.py: client-side cache backend.
  • src/cashews_mongo/registration.py: Cashews backend registration.
  • tests/unit: fast unit tests.
  • tests/integration: live MongoDB tests.
  • scripts/integration.py: integration harness.

License

Apache-2.0. See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cashews_mongo-0.1.0.tar.gz (49.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cashews_mongo-0.1.0-py3-none-any.whl (25.6 kB view details)

Uploaded Python 3

File details

Details for the file cashews_mongo-0.1.0.tar.gz.

File metadata

  • Download URL: cashews_mongo-0.1.0.tar.gz
  • Upload date:
  • Size: 49.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cashews_mongo-0.1.0.tar.gz
Algorithm Hash digest
SHA256 57c7991c3c294d70c689dafa2ac167ca78e67d9f1d3c6a1eac8dc8ef9a99dc41
MD5 4b1b75a7229a69116e8f82b724c8f640
BLAKE2b-256 306b144cccf78036962c665e94b2ce00b8915be1878b2ea416c29e14546d50b4

See more details on using hashes here.

Provenance

The following attestation bundles were made for cashews_mongo-0.1.0.tar.gz:

Publisher: release.yml on unlap-hq/cashews-mongo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file cashews_mongo-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: cashews_mongo-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cashews_mongo-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4428ecca9cd78b4d7a241d1602b368e6a0d41fd19debcb485fb17f381bf3d191
MD5 7160597c5548f6d14d6d284257679ea1
BLAKE2b-256 76151be2bb6a63a4ec0ce2e93089dd2b29519f32e4f1cccad5473ed141fdf442

See more details on using hashes here.

Provenance

The following attestation bundles were made for cashews_mongo-0.1.0-py3-none-any.whl:

Publisher: release.yml on unlap-hq/cashews-mongo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page