|
3 | 3 | # See LICENSE for details.
|
4 | 4 |
|
5 | 5 | import time
|
| 6 | +import datetime |
6 | 7 | import threading
|
7 | 8 | import os
|
8 | 9 |
|
@@ -381,3 +382,43 @@ def flush(self):
|
381 | 382 | keys = self.client.smembers(self.keys_container)
|
382 | 383 | for key in keys:
|
383 | 384 | 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