Skip to content

Instantly share code, notes, and snippets.

@joerussbowman
Created September 24, 2010 17:03
Show Gist options
  • Save joerussbowman/595684 to your computer and use it in GitHub Desktop.
Save joerussbowman/595684 to your computer and use it in GitHub Desktop.
class MongoCache(object):
def __init__(self, db, collection="cache", size=100000):
self.db = db
self.collection = collection
collections = self.db.collection_names()
if not self.collection in collections:
self.db.create_collection(self.collection, capped=True, size=size)
def set(self, k, v, ttl):
logging.warning("SET CALLED")
return self.db[self.collection].save({
"k": k,
"v": v,
"ttl": int(time.mktime(time.gmtime())) + ttl
})
def get(self, k):
hit = self.db[self.collection].find_one({"k": k,
"ttl": {"$gte": int(time.mktime(time.gmtime()))}},
sort=[('$natural', -1)])
if hit is not None:
return hit["v"]
logging.warning("HIT")
return None
def delete(self, k):
return self.db[self.collection].remove({"k": k})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment