Metadata-Version: 2.4
Name: mongoengine-rw-router
Version: 0.0.1
Summary: MongoDB read-write separation router for mongoengine ODM with transaction-aware and consistent hash routing
Project-URL: Homepage, https://github.com/pydtools/mongoengine-rw-router
Project-URL: Repository, https://github.com/pydtools/mongoengine-rw-router
Author: huoyinghui
Requires-Python: >=3.10
Requires-Dist: mongoengine>=0.27
Requires-Dist: pymongo>=4.0
Requires-Dist: uhashring>=2.1
Provides-Extra: dev
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Description-Content-Type: text/markdown

# Mongoengine Read-Write Router

A MongoDB read-write separation solution for mongoengine ODM, inspired by the [django-rw-router](https://github.com/pydtools/django-rw-router) architecture.

This library routes write operations to the primary database and read operations to replica set members, with configurable consistency strategies.

## Features

- **Automatic read-write routing** - Writes go to primary, reads go to replicas
- **Multiple consistency strategies** - random, transaction-aware, consistent hashing
- **Read-after-write consistency** - Ensures you see your own writes
- **Request context tracking** - Thread-safe context using `contextvars`
- **Web framework integration** - Middleware for FastAPI, Flask, and Django
- **Force primary reads** - Explicit control when you need fresh data
- **Write operation tracking** - Automatic context updates on writes

## Installation

```bash
pip install mongoengine-rw-router
```

## Quick Start

```python
from mongoengine import connect, Document, StringField, IntField
from mongoengine_rw_router import (
    RwDocumentMixin,
    configure,
    MongoRouterMiddleware,
)

# 1. Set up connections
connect(db="myapp", alias="default", host="mongodb://primary:27017")
connect(
    db="myapp",
    alias="replica1",
    host="mongodb://replica1:27017",
    read_preference=ReadPreference.SECONDARY_PREFERRED,
)

# 2. Configure router
configure(
    primary_alias="default",
    replica_aliases=["replica1"],
    strategy="transaction_aware",
)

# 3. Define model with routing
class User(RwDocumentMixin, Document):
    name = StringField()
    email = StringField()
    age = IntField()

    meta = {"db_alias": "default"}

# 4. Use it!
user = User.objects.first()  # Reads from replica
user.age = 25
user.save()  # Writes to primary
```

## License

MIT

## Credits

Inspired by [django-rw-router](https://github.com/pydtools/django-rw-router)
