Python 中有类似 PHP 的 Symfony Cache 组件的包吗?
Symfony Cache 组件除了实现 PSR6 接口外,还增加了 Adapter 用于存储 cache
Adapter: It implements the actual caching mechanism to store the information in the filesystem, in a database, etc. The component provides several ready to use adapters for common caching backends (Redis, APCu, Doctrine, PDO, etc.)
Python 中有类似 PHP 的 Symfony Cache 组件的包吗?
Python里没有和Symfony Cache完全对等的单一包,但有几个主流选择能覆盖类似功能。
最接近的是cachetools,它提供了基于内存的缓存装饰器(类似Symfony的ArrayCache),支持TTL和多种淘汰策略(LRU、LFU等)。对于简单的内存缓存场景,这个包很合适。
from cachetools import cached, TTLCache
import time
# 创建一个TTL缓存,最大100条,5秒过期
cache = TTLCache(maxsize=100, ttl=5)
@cached(cache)
def expensive_operation(x):
print(f"Computing {x}...")
time.sleep(1)
return x * 2
# 第一次调用会计算
print(expensive_operation(5)) # 输出: Computing 5... 然后 10
# 5秒内再次调用,直接返回缓存
print(expensive_operation(5)) # 直接输出: 10
time.sleep(6)
# TTL过期后重新计算
print(expensive_operation(5)) # 输出: Computing 5... 然后 10
如果需要文件系统或分布式缓存,diskcache是个好选择,它支持磁盘缓存和类似Memcached的客户端功能。对于更复杂的多后端支持(比如Redis、Memcached、数据库),可以用django-cache(即使不在Django项目里)或者直接组合使用redis/pymemcache等客户端库。
简单内存缓存用cachetools,需要持久化或分布式再看diskcache。
通用点的有 beaker.cache 和 dogpile.cache
web 框架和组件自带的有 django.core.cache 和 werkzeug.contrib.cache

