python MongoCache

本文介绍了一种使用MongoDB作为数据库缓存的实现方式,通过Python类MongoCache,实现了缓存的基本操作,如设置缓存项、获取缓存项、检查缓存项是否存在以及清空缓存。该缓存机制利用MongoDB的过期特性自动清理过期的缓存记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class MongoCache(object):
    """
    数据库缓存
    """
    def __init__(self,client=None,expires=timedelta(days=30)):
        self.client = MongoClient("localhost",27017)
        self.db = self.client.cache
        self.db.webpage.create_index('timestamp',expireAfterSeconds=expires.total_seconds())


    def __setitem__(self, key, value):
        record = {"result":Binary(zlib.compress(pickle.dumps(value))),"timestamp":datetime.utcnow()}
        self.db.webpage.update({"_id":key},{'$set':record},upsert=True)

    def __getitem__(self, item):
        record = self.db.webpage.find_one({"_id":item})
        if record:
            return pickle.loads(zlib.decompress(record["result"]))
        else:
            raise KeyError(item + "does not exist")

    def __contains__(self, item):
        try:
            self[item]#调用getitem方法

        except KeyError:
            return False
        else:
            return True

    def clear(self):
        self.db.webpage.drop()
    
cai_url ="http://www.runoob.com/mongodb/mongodb-insert.html"

cai_mongo = MongoCache()

cai_mongo[cai_url]=requests.get(url=cai_url).content#调用__setitem__

print(cai_mongo[cai_url].decode('utf-8'))#调用__getitem__
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值