FLYNNLABAboutMeCodingActivityStudy 2024초등수학
cachetools - python
python

python에서 간단하게 캐쉬를 사용할 수 있는 라이브러리가 있어서 소개한다.

cachetools

Support Cache

  • LFU(Least Frequently Used)
  • LRU(Least Recently Used)
  • RR(Random Replacement)
  • TTL(time-to-live)

install

pip install cachetools

usages

aggregate가 무겁긴 한데 자주 바뀌지는 않고 해서 간단히 30분짜리 캐쉬를 적용했다. python decorator를 이용해서 코드가 깔끔하다

@resolve_only_args
@func.ttl_cache(ttl=1800)
def resolve_current_devices(root):
    return [result['_id'] for result in SomeModel.objects.aggregate(
        {"$project": {"device_type": 1, "device_id": 1}},
        {"$match": {"device_type": "android"}},
        {"$group": {"_id": "$device_id", "count": {"$sum": 1}}},
        {"$sort": {"count": -1}}
    )]

Resource