symphra-cache


Namesymphra-cache JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
Summary生产级 Python 异步缓存库,支持内存、文件(热重载)、Redis 后端
upload_time2025-10-25 12:56:33
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseMIT
keywords async cache file hot-reload memory performance redis
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Symphra Cache

[English](README.md) | [中文](README.zh.md)

> 🚀 Production-grade async caching library for Python 3.11+

[![CI](https://github.com/getaix/symphra-cache/workflows/CI/badge.svg)](https://github.com/getaix/symphra-cache/actions)
[![PyPI version](https://badge.fury.io/py/symphra-cache.svg)](https://pypi.org/project/symphra-cache/)
[![Python versions](https://img.shields.io/pypi/pyversions/symphra-cache.svg)](https://pypi.org/project/symphra-cache/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code coverage](https://codecov.io/gh/symphra/symphra-cache/branch/main/graph/badge.svg)](https://codecov.io/gh/symphra/symphra-cache)

## ✨ Features

- **🎯 Three Backends**
  - **Memory**: High-performance in-memory cache with LRU eviction
  - **File**: Persistent SQLite-based cache with **hot reload** support
  - **Redis**: Distributed cache with cluster and sentinel support

- **⚡ Performance**
  - Fully async/await support
  - Memory backend: < 0.01ms latency
  - File backend: Hot reload 100k entries in < 5s
  - Redis backend: Connection pooling with hiredis acceleration

- **🔒 Advanced Features**
  - Distributed locks (Redis-based)
  - Cache warming and invalidation notifications
  - Prometheus/StatsD monitoring
  - Batch operations support

- **🎨 Developer Friendly**
  - Simple decorator API (`@cached`)
  - Context manager support (`async with cache.lock()`)
  - Type hints everywhere
  - Comprehensive Chinese documentation

## 📦 Installation

```bash
# Basic installation (uv - recommended)
uv add symphra-cache

# Or with pip
pip install symphra-cache

# With Redis support
uv add symphra-cache redis

# Full installation (all features)
pip install symphra-cache[all]
```


### Monitoring

```python
from symphra_cache import CacheManager, CacheMonitor
from symphra_cache.monitoring.prometheus import PrometheusExporter
from symphra_cache.monitoring.statsd import StatsDExporter

# Enable monitoring
cache = CacheManager.from_config({"backend": "memory"})
monitor = CacheMonitor(cache)

# Do some operations
cache.set("user:1", {"name": "Alice"})
cache.get("user:1")

# Unified metrics API
metrics = monitor.metrics
print(metrics.get_latency_stats("get"))  # {"min": ..., "max": ..., "avg": ...}

# Prometheus text metrics
prom = PrometheusExporter(monitor, namespace="myapp", subsystem="cache")
print(prom.generate_metrics())

# StatsD exporter (requires reachable server if sending)
statsd = StatsDExporter(monitor, prefix="myapp.cache")
# await statsd.send_metrics()  # in async context
```

- Install monitoring extras: `pip install symphra-cache[monitoring]`
- Provides Prometheus/StatsD exporters with hit/miss, counts, and latency stats.

## 🚀 Quick Start

### Basic Usage

```python
from symphra_cache import CacheManager
from symphra_cache.backends import MemoryBackend

# Create cache manager with memory backend
cache = CacheManager(backend=MemoryBackend())

# Basic operations
cache.set("user:123", {"name": "Alice", "age": 30}, ttl=3600)
user = cache.get("user:123")

# Async operations
await cache.aset("product:456", {"name": "Laptop", "price": 999})
product = await cache.aget("product:456")
```

### File Backend with Hot Reload

```python
from symphra_cache.backends import FileBackend

# Create file backend (persists to SQLite)
backend = FileBackend(db_path="./cache.db")
cache = CacheManager(backend=backend)

# Set cache (persisted immediately)
cache.set("session:xyz", {"user_id": 123}, ttl=1800)

# Restart process... cache automatically reloads!
# The data is still available after restart
session = cache.get("session:xyz")  # ✅ Works!
```

### Decorator API

```python
from symphra_cache.decorators import acache

@acache(cache, ttl=300)
async def get_user_profile(user_id: int):
    """Fetch user profile (cached for 5 minutes)"""
    return await database.fetch_user(user_id)

# First call: queries database
profile = await get_user_profile(123)

# Second call: returns from cache
profile = await get_user_profile(123)  # ⚡ Fast!
```

### Distributed Lock

```python
from symphra_cache.backends import RedisBackend
from symphra_cache.locks import DistributedLock

cache = CacheManager(backend=RedisBackend())
lock = DistributedLock(cache, "critical_resource", timeout=30)

with lock:
    # Only one instance can execute this block at a time
    value = cache.get("counter") or 0
    cache.set("counter", value + 1)
```

## 📚 Documentation

- **English Docs**: [https://symphra-cache.readthedocs.io/en/](https://symphra-cache.readthedocs.io/en/)
- **中文文档**: [https://symphra-cache.readthedocs.io/zh/](https://symphra-cache.readthedocs.io/zh/)

### Topics

- [Getting Started](docs/en/quickstart.md)
- [Backends](docs/en/backends/)
  - [Memory Backend](docs/en/backends/memory.md)
  - [File Backend (Hot Reload)](docs/en/backends/file.md)
  - [Redis Backend](docs/en/backends/redis.md)
- [Advanced Features](docs/en/advanced/)
  - [Distributed Locks](docs/en/advanced/locks.md)
  - [Cache Warming](docs/en/advanced/warming.md)
  - [Monitoring](docs/en/advanced/monitoring.md)
- [API Reference](docs/en/api/reference.md)

## 🏗️ Architecture

```
┌──────────────────────────────────────┐
│      Unified API (CacheManager)      │
│  @cached | async with cache.lock()  │
└──────────┬───────────┬───────────────┘
           │           │
    ┌──────▼─────┐ ┌──▼────┐ ┌────────┐
    │   Memory   │ │ File  │ │ Redis  │
    │  Backend   │ │Backend│ │Backend │
    │            │ │       │ │        │
    │ - Dict     │ │SQLite │ │redis-py│
    │ - LRU      │ │+Memory│ │+hiredis│
    │ - TTL      │ │Hot    │ │Cluster │
    └────────────┘ │Reload │ └────────┘
                   └───────┘
```

## 🔬 Performance

| Backend | Read (P99) | Write (P99) | Throughput | Hot Reload (100k) |
|---------|-----------|------------|-----------|-------------------|
| Memory  | < 0.01ms  | < 0.01ms   | 200k ops/s | N/A              |
| File    | < 0.1ms   | < 1ms      | 50k ops/s  | < 5s             |
| Redis   | < 1ms     | < 2ms      | 100k ops/s | N/A              |

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🔗 Links

- **GitHub**: [https://github.com/getaix/symphra-cache](https://github.com/getaix/symphra-cache)
- **PyPI**: [https://pypi.org/project/symphra-cache/](https://pypi.org/project/symphra-cache/)
- **Documentation**: [https://getaix.github.io/symphra-cache/](https://getaix.github.io/symphra-cache/)
- **Issues**: [https://github.com/getaix/symphra-cache/issues](https://github.com/getaix/symphra-cache/issues)
- **Changelog**: [CHANGELOG.md](CHANGELOG.md)

## 🌟 Star History

[![Star History Chart](https://api.star-history.com/svg?repos=symphra/symphra-cache&type=Date)](https://star-history.com/#symphra/symphra-cache&Date)

---

Made with ❤️ by the Symphra Team

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "symphra-cache",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "async, cache, file, hot-reload, memory, performance, redis",
    "author": null,
    "author_email": "Symphra Team <dev@symphra.com>",
    "download_url": "https://files.pythonhosted.org/packages/2e/43/1b6e029200d958a8130bc2db743b1817c67adda5fe534eff2db9b53194bb/symphra_cache-0.1.0.tar.gz",
    "platform": null,
    "description": "# Symphra Cache\n\n[English](README.md) | [\u4e2d\u6587](README.zh.md)\n\n> \ud83d\ude80 Production-grade async caching library for Python 3.11+\n\n[![CI](https://github.com/getaix/symphra-cache/workflows/CI/badge.svg)](https://github.com/getaix/symphra-cache/actions)\n[![PyPI version](https://badge.fury.io/py/symphra-cache.svg)](https://pypi.org/project/symphra-cache/)\n[![Python versions](https://img.shields.io/pypi/pyversions/symphra-cache.svg)](https://pypi.org/project/symphra-cache/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Code coverage](https://codecov.io/gh/symphra/symphra-cache/branch/main/graph/badge.svg)](https://codecov.io/gh/symphra/symphra-cache)\n\n## \u2728 Features\n\n- **\ud83c\udfaf Three Backends**\n  - **Memory**: High-performance in-memory cache with LRU eviction\n  - **File**: Persistent SQLite-based cache with **hot reload** support\n  - **Redis**: Distributed cache with cluster and sentinel support\n\n- **\u26a1 Performance**\n  - Fully async/await support\n  - Memory backend: < 0.01ms latency\n  - File backend: Hot reload 100k entries in < 5s\n  - Redis backend: Connection pooling with hiredis acceleration\n\n- **\ud83d\udd12 Advanced Features**\n  - Distributed locks (Redis-based)\n  - Cache warming and invalidation notifications\n  - Prometheus/StatsD monitoring\n  - Batch operations support\n\n- **\ud83c\udfa8 Developer Friendly**\n  - Simple decorator API (`@cached`)\n  - Context manager support (`async with cache.lock()`)\n  - Type hints everywhere\n  - Comprehensive Chinese documentation\n\n## \ud83d\udce6 Installation\n\n```bash\n# Basic installation (uv - recommended)\nuv add symphra-cache\n\n# Or with pip\npip install symphra-cache\n\n# With Redis support\nuv add symphra-cache redis\n\n# Full installation (all features)\npip install symphra-cache[all]\n```\n\n\n### Monitoring\n\n```python\nfrom symphra_cache import CacheManager, CacheMonitor\nfrom symphra_cache.monitoring.prometheus import PrometheusExporter\nfrom symphra_cache.monitoring.statsd import StatsDExporter\n\n# Enable monitoring\ncache = CacheManager.from_config({\"backend\": \"memory\"})\nmonitor = CacheMonitor(cache)\n\n# Do some operations\ncache.set(\"user:1\", {\"name\": \"Alice\"})\ncache.get(\"user:1\")\n\n# Unified metrics API\nmetrics = monitor.metrics\nprint(metrics.get_latency_stats(\"get\"))  # {\"min\": ..., \"max\": ..., \"avg\": ...}\n\n# Prometheus text metrics\nprom = PrometheusExporter(monitor, namespace=\"myapp\", subsystem=\"cache\")\nprint(prom.generate_metrics())\n\n# StatsD exporter (requires reachable server if sending)\nstatsd = StatsDExporter(monitor, prefix=\"myapp.cache\")\n# await statsd.send_metrics()  # in async context\n```\n\n- Install monitoring extras: `pip install symphra-cache[monitoring]`\n- Provides Prometheus/StatsD exporters with hit/miss, counts, and latency stats.\n\n## \ud83d\ude80 Quick Start\n\n### Basic Usage\n\n```python\nfrom symphra_cache import CacheManager\nfrom symphra_cache.backends import MemoryBackend\n\n# Create cache manager with memory backend\ncache = CacheManager(backend=MemoryBackend())\n\n# Basic operations\ncache.set(\"user:123\", {\"name\": \"Alice\", \"age\": 30}, ttl=3600)\nuser = cache.get(\"user:123\")\n\n# Async operations\nawait cache.aset(\"product:456\", {\"name\": \"Laptop\", \"price\": 999})\nproduct = await cache.aget(\"product:456\")\n```\n\n### File Backend with Hot Reload\n\n```python\nfrom symphra_cache.backends import FileBackend\n\n# Create file backend (persists to SQLite)\nbackend = FileBackend(db_path=\"./cache.db\")\ncache = CacheManager(backend=backend)\n\n# Set cache (persisted immediately)\ncache.set(\"session:xyz\", {\"user_id\": 123}, ttl=1800)\n\n# Restart process... cache automatically reloads!\n# The data is still available after restart\nsession = cache.get(\"session:xyz\")  # \u2705 Works!\n```\n\n### Decorator API\n\n```python\nfrom symphra_cache.decorators import acache\n\n@acache(cache, ttl=300)\nasync def get_user_profile(user_id: int):\n    \"\"\"Fetch user profile (cached for 5 minutes)\"\"\"\n    return await database.fetch_user(user_id)\n\n# First call: queries database\nprofile = await get_user_profile(123)\n\n# Second call: returns from cache\nprofile = await get_user_profile(123)  # \u26a1 Fast!\n```\n\n### Distributed Lock\n\n```python\nfrom symphra_cache.backends import RedisBackend\nfrom symphra_cache.locks import DistributedLock\n\ncache = CacheManager(backend=RedisBackend())\nlock = DistributedLock(cache, \"critical_resource\", timeout=30)\n\nwith lock:\n    # Only one instance can execute this block at a time\n    value = cache.get(\"counter\") or 0\n    cache.set(\"counter\", value + 1)\n```\n\n## \ud83d\udcda Documentation\n\n- **English Docs**: [https://symphra-cache.readthedocs.io/en/](https://symphra-cache.readthedocs.io/en/)\n- **\u4e2d\u6587\u6587\u6863**: [https://symphra-cache.readthedocs.io/zh/](https://symphra-cache.readthedocs.io/zh/)\n\n### Topics\n\n- [Getting Started](docs/en/quickstart.md)\n- [Backends](docs/en/backends/)\n  - [Memory Backend](docs/en/backends/memory.md)\n  - [File Backend (Hot Reload)](docs/en/backends/file.md)\n  - [Redis Backend](docs/en/backends/redis.md)\n- [Advanced Features](docs/en/advanced/)\n  - [Distributed Locks](docs/en/advanced/locks.md)\n  - [Cache Warming](docs/en/advanced/warming.md)\n  - [Monitoring](docs/en/advanced/monitoring.md)\n- [API Reference](docs/en/api/reference.md)\n\n## \ud83c\udfd7\ufe0f Architecture\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502      Unified API (CacheManager)      \u2502\n\u2502  @cached | async with cache.lock()  \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n           \u2502           \u2502\n    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u25bc\u2500\u2500\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u25bc\u2500\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    \u2502   Memory   \u2502 \u2502 File  \u2502 \u2502 Redis  \u2502\n    \u2502  Backend   \u2502 \u2502Backend\u2502 \u2502Backend \u2502\n    \u2502            \u2502 \u2502       \u2502 \u2502        \u2502\n    \u2502 - Dict     \u2502 \u2502SQLite \u2502 \u2502redis-py\u2502\n    \u2502 - LRU      \u2502 \u2502+Memory\u2502 \u2502+hiredis\u2502\n    \u2502 - TTL      \u2502 \u2502Hot    \u2502 \u2502Cluster \u2502\n    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502Reload \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\n## \ud83d\udd2c Performance\n\n| Backend | Read (P99) | Write (P99) | Throughput | Hot Reload (100k) |\n|---------|-----------|------------|-----------|-------------------|\n| Memory  | < 0.01ms  | < 0.01ms   | 200k ops/s | N/A              |\n| File    | < 0.1ms   | < 1ms      | 50k ops/s  | < 5s             |\n| Redis   | < 1ms     | < 2ms      | 100k ops/s | N/A              |\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\udd17 Links\n\n- **GitHub**: [https://github.com/getaix/symphra-cache](https://github.com/getaix/symphra-cache)\n- **PyPI**: [https://pypi.org/project/symphra-cache/](https://pypi.org/project/symphra-cache/)\n- **Documentation**: [https://getaix.github.io/symphra-cache/](https://getaix.github.io/symphra-cache/)\n- **Issues**: [https://github.com/getaix/symphra-cache/issues](https://github.com/getaix/symphra-cache/issues)\n- **Changelog**: [CHANGELOG.md](CHANGELOG.md)\n\n## \ud83c\udf1f Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=symphra/symphra-cache&type=Date)](https://star-history.com/#symphra/symphra-cache&Date)\n\n---\n\nMade with \u2764\ufe0f by the Symphra Team\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "\u751f\u4ea7\u7ea7 Python \u5f02\u6b65\u7f13\u5b58\u5e93\uff0c\u652f\u6301\u5185\u5b58\u3001\u6587\u4ef6\uff08\u70ed\u91cd\u8f7d\uff09\u3001Redis \u540e\u7aef",
    "version": "0.1.0",
    "project_urls": {
        "Changelog": "https://github.com/getaix/symphra-cache/blob/main/CHANGELOG.md",
        "Documentation": "https://getaix.github.io/symphra-cache/",
        "Homepage": "https://github.com/getaix/symphra-cache",
        "Issues": "https://github.com/getaix/symphra-cache/issues",
        "Repository": "https://github.com/getaix/symphra-cache"
    },
    "split_keywords": [
        "async",
        " cache",
        " file",
        " hot-reload",
        " memory",
        " performance",
        " redis"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f125a347df6a6b14027f51ab00f78196be23a6e14964b8e43a7a0ed47f6d68ba",
                "md5": "d2d57afdc35e1cd0528e43879fb0e841",
                "sha256": "29d0ffea2b08a901e4db5a67ea4a950dbb4d63453efb9e236493655dbe8bceb9"
            },
            "downloads": -1,
            "filename": "symphra_cache-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d2d57afdc35e1cd0528e43879fb0e841",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 67167,
            "upload_time": "2025-10-25T12:56:31",
            "upload_time_iso_8601": "2025-10-25T12:56:31.520146Z",
            "url": "https://files.pythonhosted.org/packages/f1/25/a347df6a6b14027f51ab00f78196be23a6e14964b8e43a7a0ed47f6d68ba/symphra_cache-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2e431b6e029200d958a8130bc2db743b1817c67adda5fe534eff2db9b53194bb",
                "md5": "5fffa5e08cb07557517ed3dd79d3cc75",
                "sha256": "4aa163f4809edc539968d8dcee17921731fa84b13815da3ee206d98adb2ad88f"
            },
            "downloads": -1,
            "filename": "symphra_cache-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "5fffa5e08cb07557517ed3dd79d3cc75",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 124828,
            "upload_time": "2025-10-25T12:56:33",
            "upload_time_iso_8601": "2025-10-25T12:56:33.837964Z",
            "url": "https://files.pythonhosted.org/packages/2e/43/1b6e029200d958a8130bc2db743b1817c67adda5fe534eff2db9b53194bb/symphra_cache-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-25 12:56:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "getaix",
    "github_project": "symphra-cache",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "symphra-cache"
}
        
Elapsed time: 1.41199s