Skip to content

Commit 2e7638e

Browse files
author
Wladston Viana Ferreira Filho
committed
MongoDB cache backend added.
1 parent d2cc201 commit 2e7638e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tweepy/cache.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# See LICENSE for details.
44

55
import time
6+
import datetime
67
import threading
78
import os
89

@@ -381,3 +382,43 @@ def flush(self):
381382
keys = self.client.smembers(self.keys_container)
382383
for key in keys:
383384
self.delete_entry(key)
385+
386+
387+
class MongodbCache(Cache):
388+
"""A simple pickle-based MongoDB cache sytem."""
389+
390+
def __init__(self, db, timeout=3600, collection='tweepy_cache'):
391+
"""Should receive a "database" cursor from pymongo."""
392+
Cache.__init__(self, timeout)
393+
self.timeout = timeout
394+
self.col = db[collection]
395+
self.col.create_index('created', expireAfterSeconds=timeout)
396+
397+
def store(self, key, value):
398+
from bson.binary import Binary
399+
400+
now = datetime.datetime.utcnow()
401+
blob = Binary(pickle.dumps(value))
402+
403+
self.col.insert({'created': now, '_id': key, 'value': blob})
404+
405+
def get(self, key, timeout=None):
406+
if timeout:
407+
raise NotImplementedError
408+
obj = self.col.find_one({'_id': key})
409+
if obj:
410+
return pickle.loads(obj['value'])
411+
412+
def count(self):
413+
return self.col.find({}).count()
414+
415+
def delete_entry(self, key):
416+
return self.col.remove({'_id': key})
417+
418+
def cleanup(self):
419+
"""MongoDB will automatically clear expired keys."""
420+
pass
421+
422+
def flush(self):
423+
self.col.drop()
424+
self.col.create_index('created', expireAfterSeconds=self.timeout)

0 commit comments

Comments
 (0)