Skip to main content

Use Cache

一个框架无关的Python缓存库,支持多种后端和框架集成。

特性

  • 🚀 框架无关: 可以与任何Python框架集成,不仅限于FastAPI
  • 🔧 多后端支持: 支持Redis、Memcached、DynamoDB和内存缓存
  • 🎯 类型安全: 完整的类型注解支持
  • 🔄 异步优先: 原生异步支持,同时兼容同步函数
  • 🎨 灵活配置: 支持自定义编码器、键构建器和过期策略
  • 📦 向后兼容: 与fastapi-cache完全兼容

安装

# 基础安装
pip install use-cache

# 安装Redis支持
pip install use-cache[redis]

# 安装Memcached支持  
pip install use-cache[memcached]

# 安装DynamoDB支持
pip install use-cache[dynamodb]

# 安装所有后端
pip install use-cache[all]

快速开始

基本使用

import asyncio
from use_cache import CacheManager, InMemoryBackend, JsonCoder

async def main():
    # 初始化缓存管理器
    cache_manager = CacheManager()
    await cache_manager.init(
        backend=InMemoryBackend(),
        coder=JsonCoder(),
        prefix="myapp:",
        expire=300  # 5分钟
    )
    
    # 手动缓存操作
    await cache_manager.set("user:123", {"name": "Alice", "age": 30})
    user = await cache_manager.get("user:123")
    print(user)  # {'name': 'Alice', 'age': 30}

asyncio.run(main())

装饰器使用

from use_cache import cache, CacheManager, InMemoryBackend, JsonCoder

# 初始化缓存(通常在应用启动时)
async def setup_cache():
    cache_manager = CacheManager()
    await cache_manager.init(
        backend=InMemoryBackend(),
        coder=JsonCoder()
    )

@cache(expire=60)
async def get_user_data(user_id: int):
    # 模拟数据库查询
    return {"id": user_id, "name": f"User {user_id}"}

# 使用
await setup_cache()
user = await get_user_data(123)  # 第一次调用,执行函数
user = await get_user_data(123)  # 第二次调用,使用缓存

FastAPI集成

from fastapi import FastAPI
from use_cache import CacheManager, InMemoryBackend, JsonCoder
from use_cache.integrations.fastapi import cache

app = FastAPI()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize cache on startup
    CacheManager.init(
        backend=InMemoryBackend(),
        coder=JsonCoder,
        prefix="fastapi:",
        expire=300  # 5 minutes
    )
    yield
    # Cleanup on shutdown (if needed)

@app.get("/users/{user_id}")
@cache(expire=60)
async def get_user(user_id: int):
    return {"id": user_id, "name": f"User {user_id}"}

支持的后端

内存缓存

from use_cache import InMemoryBackend

backend = InMemoryBackend()

Redis

from use_cache import RedisBackend

# 单个Redis实例
backend = RedisBackend("redis://localhost:6379")

# Redis集群
backend = RedisBackend([
    "redis://node1:6379",
    "redis://node2:6379", 
    "redis://node3:6379"
])

Memcached

from use_cache import MemcachedBackend

backend = MemcachedBackend("127.0.0.1", 11211)

DynamoDB

from use_cache import DynamoDBBackend

backend = DynamoDBBackend(
    table_name="cache_table",
    region_name="us-east-1"
)

编码器

JSON编码器(默认)

from use_cache import JsonCoder

coder = JsonCoder()

Pickle编码器

from use_cache import PickleCoder

coder = PickleCoder()

字符串编码器

from use_cache import StringCoder

coder = StringCoder()

键构建器

默认键构建器

from use_cache import default_key_builder

# 自动根据函数名和参数生成键

简单键构建器

from use_cache import simple_key_builder

# 仅使用函数名作为键

自定义键构建器

def custom_key_builder(func, *args, **kwargs):
    return f"custom:{func.__name__}:{hash(str(args) + str(kwargs))}"

便捷装饰器

from use_cache import cache_one_minute, cache_one_hour, cache_one_day

@cache_one_minute
async def quick_data():
    return "cached for 1 minute"

@cache_one_hour  
async def hourly_data():
    return "cached for 1 hour"

@cache_one_day
async def daily_data():
    return "cached for 1 day"

开发

安装开发依赖

uv sync --extra test
# 如需安装后端支持,可选择性同步对应 extras:
# Redis:      uv sync --extra redis
# Memcached:  uv sync --extra memcached
# DynamoDB:   uv sync --extra dynamodb
# 全部后端:   uv sync --extra all

运行测试

uv run pytest

运行示例

# 基本示例
uv run python examples/basic_usage.py

# FastAPI示例
uv run python examples/fastapi_example.py

许可证

MIT License

Metadata

Release files for use-cache 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for use-cache 0.1.0
File Size Uploaded Provenance
use_cache-0.1.0.tar.gz 11.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for use-cache 0.1.0
File Interpreter ABI Platform
use_cache-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 29.7 kB

Release files / use_cache-0.1.0.tar.gz

Download URL use_cache-0.1.0.tar.gz
Size 11.7 kB
Tags Source
SHA-256 checksum
How to use checksums
2f20e4ef887a798ef6e94863ef096714d484894d4a86d2b1616898ebd0f7e5fd
BLAKE2b-256 checksum
How to use checksums
a16a21dab8c24f75263fc82b45ea9d6be919eb233a00bbc1d937f631d9d3c5b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.13

Release files / use_cache-0.1.0-py3-none-any.whl

Download URL use_cache-0.1.0-py3-none-any.whl
Size 18.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cbb981f69955fcfeec03452c29f4862bea9cf9805b59d54fe84810e9e5440cae
BLAKE2b-256 checksum
How to use checksums
95dcf18a389afa30c8ef0fff7842f7d12dc3a65c4db244499677e5b6b8bbf666
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.13

Security for use-cache 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page