a fast cache support complex data
Project description
# YCache
YCache 是一个高性能的 Python 缓存工具库,提供了基于 orjson 的内存缓存实现,支持 TTL(生存时间)和 LRU(最近最少使用)淘汰策略。
## 特性
- 🚀 高性能:使用 orjson 进行快速序列化
- 🔄 序列化选项:支持 pickle 和 orjson 序列化(推荐使用 orjson)
- ⏱️ TTL 支持:可设置缓存项的过期时间
- 🎯 类型感知:支持参数类型敏感的缓存
- 🧵 线程安全:支持多线程访问
- 🛡️ 安全性:推荐使用 orjson 序列化以提高安全性
## 安装
```bash
pip install ycache
快速开始
基本使用
from ycache import orjson_lru_cache
@orjson_lru_cache(maxsize=128, ttl=60)
def expensive_operation(x: int) -> int:
# 一些耗时的操作
return x * 2
# 第一次调用:执行函数
result = expensive_operation(42)
# 第二次调用:使用缓存
result = expensive_operation(42)
高级特性
1. 类型敏感缓存
from ycache import orjson_lru_cache
@orjson_lru_cache(typed=True)
def process_data(value):
return {"value": value}
# 这两次调用会分别缓存,因为参数类型不同
result1 = process_data(1) # 整数参数
result2 = process_data(1.0) # 浮点数参数
2. 缓存大小限制
from ycache import orjson_lru_cache
@orjson_lru_cache(maxsize=2)
def get_data(key: str):
return f"Data for {key}"
# 只保留最近使用的两个结果
get_data("A") # 缓存
get_data("B") # 缓存
get_data("C") # 缓存,移除 A 的缓存
get_data("A") # 重新计算
3. 复杂对象缓存
from ycache import orjson_lru_cache, disk_cache
from datetime import datetime
from dataclasses import dataclass
import numpy as np
@dataclass
class UserProfile:
id: int
name: str
scores: np.ndarray
created_at: datetime
metadata: dict
# 内存缓存:适合频繁访问的小型数据
@orjson_lru_cache(maxsize=1000, ttl=300)
def get_user_profile(user_id: int) -> UserProfile:
return UserProfile(
id=user_id,
name=f"User_{user_id}",
scores=np.array([95, 87, 92]),
created_at=datetime.now(),
metadata={"last_login": "2023-01-01"}
)
# 磁盘缓存:适合大型数据或需要持久化的数据
@disk_cache(
cache_dir='.cache/users',
ttl=3600,
serializer='orjson' # 使用 orjson 序列化
)
def get_user_analytics(user_id: int) -> dict:
# 模拟复杂的数据分析结果
return {
"user_id": user_id,
"activity_data": {
"daily_logins": [1, 0, 1, 1, 0],
"session_times": [120, 45, 30, 60],
"feature_usage": {
"chat": 0.8,
"profile": 0.6,
"settings": 0.2
}
},
"performance_metrics": {
"response_times": [0.1, 0.2, 0.15],
"error_rates": [0.01, 0.02, 0.01],
"success_rate": 0.98
},
"recommendations": [
{"id": 1, "score": 0.9},
{"id": 2, "score": 0.8},
{"id": 3, "score": 0.7}
],
"timestamp": datetime.now().isoformat()
}
# 使用示例
user = get_user_profile(1) # 从内存缓存获取
analytics = get_user_analytics(1) # 从磁盘缓存获取
4. 缓存信息和控制
from ycache import orjson_lru_cache
@orjson_lru_cache(maxsize=100)
def calculate(n: int):
return n * n
# 执行一些操作
calculate(1)
calculate(2)
calculate(1) # 缓存命中
# 获取缓存统计信息
info = calculate.cache_info()
print(f"命中次数: {info.hits}")
print(f"未命中次数: {info.misses}")
print(f"最大大小: {info.maxsize}")
print(f"当前大小: {info.currsize}")
# 清理缓存
calculate.cache_clear()
5. 错误处理
from ycache import orjson_lru_cache
@orjson_lru_cache()
def process_data(data):
if not isinstance(data, (dict, list)):
raise ValueError("Invalid data type")
return data
# 正常情况
result = process_data({"key": "value"})
# 错误情况会正常抛出异常
try:
result = process_data(complex(1, 2)) # 不支持的类型
except TypeError:
print("不支持的数据类型")
最佳实践
-
使用
orjson_lru_cache而不是pickled_lru_cache:- 更好的性能
- 更安全的序列化机制
- 更好的类型支持
-
合理设置
maxsize:- 太小可能导致频繁缓存失效
- 太大可能占用过多内存
- 建议根据实际使用场景进行调整
-
合理设置
ttl:- 根据数据更新频率设置
- 避免缓存过期数据
- 默认值为 10 秒
-
类型敏感缓存:
- 当参数类型重要时使用
typed=True - 注意可能增加内存使用
- 当参数类型重要时使用
-
选择合适的缓存类型:
-
内存缓存 (
orjson_lru_cache):- 适用于频繁访问的小型数据
- 适用于临时数据
- 重启后数据会丢失
- 受内存大小限制
-
磁盘缓存 (
disk_cache):- 适用于大型数据集
- 适用于需要持久化的数据
- 重启后数据仍然保留
- 受磁盘空间限制
- 访问速度相对较慢
-
-
磁盘缓存最佳实践:
- 合理设置缓存目录:
- 使用专门的缓存目录
- 确保目录具有适当的读写权限
- 选择合适的序列化方式:
- 推荐使用 'orjson' 序列化
- 对于特殊对象可以使用 'pickle'
- 定期清理:
- 设置合理的 TTL
- 实现定期清理机制
- 错误处理:
- 处理磁盘空间不足的情况
- 处理权限问题
- 处理并发访问冲突
- 合理设置缓存目录:
注意事项
-
序列化限制:
- orjson 不支持所有 Python 类型(如复数)
- 使用不支持的类型时会自动降级为直接调用
-
内存使用:
- 注意监控缓存大小
- 适时清理不需要的缓存
-
线程安全:
- 缓存操作是线程安全的
- 但被装饰的函数需要自行保证线程安全
许可证
MIT License
测试覆盖度
--------- coverage: platform darwin, python 3.11.11-final-0 ----------
Name Stmts Miss Cover
-------------------------------------------------
tests/__init__.py 0 0 100%
tests/test_disk_cache.py 153 19 88%
tests/test_orjson_cache.py 226 14 94%
tests/test_pickled_cache.py 103 0 100%
ycache/__init__.py 3 0 100%
ycache/core.py 195 18 91%
ycache/disk_cache.py 30 0 100%
-------------------------------------------------
TOTAL 710 51 93%
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
ycache-0.3.8.tar.gz
(7.3 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ycache-0.3.8.tar.gz.
File metadata
- Download URL: ycache-0.3.8.tar.gz
- Upload date:
- Size: 7.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.11.11 Darwin/23.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4ca4417ea144e11144af4e1d06556b1902ee1c8cfca47dbf044517887399bd51
|
|
| MD5 |
84eff69a33c6753acb41e298d27dd01e
|
|
| BLAKE2b-256 |
871284684459f70158942053c6ca4a073c0cee2ae08e8ecd2ba516ba7982873b
|
File details
Details for the file ycache-0.3.8-py3-none-any.whl.
File metadata
- Download URL: ycache-0.3.8-py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.11.11 Darwin/23.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dc0aafbc5d6c6e68375d2afb4c4286270d06582952c8d408d935d3a2262f1b60
|
|
| MD5 |
a59eb879f81eb4d3749cb0cbe59b3b49
|
|
| BLAKE2b-256 |
03d5efa9585a8c777bd817978e21b65a45bd4a84b739032413612cefafd77e7c
|